所以我的第一項任務就是製作一個簡單的問題和答案程序。用戶提出問題,並且我生成一個答案。我從來沒有做過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循環時,它會卡在指定的點。 幫助不大。謝謝。
什麼是錯誤? – kosa
上面編輯,忘記了,對不起。我有點理解錯誤。我只是不明白爲什麼會發生。 – de1337ed
始終確保可通過調用(sc.hasNext()){ }然後您的代碼進行輸入。 } – kosa