[英]New to java. Error using scanner class in while loop?
因此,我的第一個任務是制作一個簡單的問答程序。 用戶問一個問題,我就產生一個答案。 我從來沒有做過Java。 這是我的輸入類:
//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循環時,它停留在指示的位置。 沒什么幫助。 謝謝。
我注意到的一件事:您可能不應該在掃描儀上調用close()
。 根據JavaDocs ,您正在關閉基礎輸入流(標准輸入)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.