2015-01-13 16 views
1

以及IM學習java我自己,但據我所知,我只是不能似乎解決這個問題 目前正在測試一個腳本,你若不輸入烏爾名字正是ü必須重新輸入,但這個錯誤看來我到處搜尋,但大多數的事情我想不工作而在Java環路誤差目前

Please type in your name: 
lucas 
Welcome lucas 
Confirm your name: 
luca 
Please type in your name: 
Exception in thread "main" java.util.NoSuchElementException: No line found 
at java.util.Scanner.nextLine(Unknown Source) 
at input.main(input.java:9) 

這裏是代碼:

import java.util.Scanner; 

public class input { 
    public static void main(String[] args) { 

     while (true) { 
      try (Scanner input = new Scanner(System.in)) { 
       System.out.println("Please type in your name: "); 
       String name = input.nextLine(); 
       System.out.println("Welcome " + name); 
       if (name.equals("nico")) { 
        System.out.println("bitch"); 
        break; 
       } else { 
        System.out.println("Confirm your name:"); 
        String name1 = input.nextLine(); 
        if (name1.equals("nico")) { 
         System.out.println("Hello " + name1 + "... bitch"); 
        } else if (name1.equals(name)) { 
         System.out.println("Thank you"); 
         break; 
        } 
       } 
      } 
     } 
    } 
} 
+0

歡迎SO。請參閱[問] –

+0

你用什麼輸入得到上面的輸出?所述NoSuchElementException異常被升高,因爲'Scanner.nextLine()'未找到另一條線。 – hhafez

回答

2

移動try-with-resources到周圍的while循環。在執行離開try-with-resources,爪哇關閉資源。在這裏,該資源是標準輸入,不能重新打開。

try (Scanner input = new Scanner(System.in)) { 
    while (true) { 
     System.out.println("Please type in your name: "); 

你其實並不真的需要這裏的try-with-resources。不要關閉標準輸入/輸出/錯誤。

+0

現在我今天學到了東西!有興趣的Documentationf:http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#close() –

+0

我相信我沒有注意到...我現在覺得很笨 但我們可以說我刪除了'try-with-resources',它的左邊是這樣的: \t \t'Scanner input = new Scanner(System.in); \t \t而(真){ \t \t \t的System.out.println( 「請輸入您的姓名:」);' 的IDE告訴我資源泄露:在 '輸入' 永遠不會關閉。除非我保留'try-with-resources' – lucas

+0

@lucas這是一個警告。你可以選擇忽略它。在這種情況下,你應該忽略它。 –

1

不要把Scanner轉換成你的循環。

循環,而掃描儀仍然有輸入。

目前,你創建new Scanner太頻繁。