2012-08-30 51 views
2

所以我的第一項任務就是製作一個簡單的問題和答案程序。用戶提出問題,並且我生成一個答案。我從來沒有做過Java。這裏是我的輸入級:新來java。在while循環中使用掃描儀類時出錯?

//msg is the msg I output (answer to their question). 
//Function returns inputStr which is the question the user asks. 
public String getInput(String msg) { 
    System.out.println(msg); 
    Scanner theInput = new Scanner(System.in); 
    String inputStr = theInput.nextLine(); //ERROR HERE ON 2nd ITERATION! 
    theInput.close(); 
    if (inputStr.equals("exit")) { 
     System.out.println("GoodBye!"); 
     System.exit(0); 
    } 
    return inputStr; 
} 

,在while循環調用此函數如下:

//inputSource is an object that has the getInput method. It is an argument for this function. 
    String userQuestion = inputSource.getInput(firstLine); 
    String initMsg = processMessage(userQuestion); 
    while(!initMsg.equalsIgnoreCase("GoodBye")){ 
     userQuestion = inputSource.getInput(initMsg); 
     //Doesn't get to here. 
     initMsg = processMessage(userQuestion); 
    } 
    System.out.println(initMsg); 

錯誤:

Exception in thread "main" java.util.NoSuchElementException: No line found 
at java.util.Scanner.nextLine(Scanner.java:1516) 

因此,基本上,是它發生了什麼問一次問題,然後回答一次,但是當它進入while循環時,它會卡在指定的點。 幫助不大。謝謝。

+0

什麼是錯誤? – kosa

+0

上面編輯,忘記了,對不起。我有點理解錯誤。我只是不明白爲什麼會發生。 – de1337ed

+0

始終確保可通過調用(sc.hasNext()){ }然後您的代碼進行輸入。 } – kosa

回答

4

我注意到的一件事:您應該不要在掃描儀上撥打close()。根據JavaDocs,您正在關閉基礎輸入流(標準輸入)。

+0

哇,修正了它。你能給我更詳細的信息,說明它是如何修復的嗎? – de1337ed

+1

'System.in'流與C中的'stdin'等價。它通常不應該被關閉。當你在掃描器上調用'close()'時,JavaDocs聲明'如果它的底層可讀也實現了Closeable接口,那麼可讀的close方法將被調用.'在這種情況下,「底層可讀」是'System.in' 。如果你關閉它,你將無法獲得更多的輸入。 =) – mpontillo