So my first assignment involves making a simple question and answer program. The user asks a question, and I generate an answer. I’ve never done java before. Here is my input class:
//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;
}
The function that calls this in the while loop is as follows:
//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);
Error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
So basically, what happens is that it asks a question once, and then it gives back an answer once, but when it enters the while loop, it gets stuck at the indicated point.
Little help. Thank you.
One thing that I noticed: you should probably not call
close()on the scanner. You’re closing the underlying input stream (standard input), according to the JavaDocs.