所以我的第一个任务是制作一个简单的问答程序。用户提出问题,我生成答案。我以前从来没有做过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,您正在关闭底层输入流(标准输入) .
关于java - 刚接触java。在 while 循环中使用扫描仪类时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12200299/