そこで、私の最初の課題は、簡単な質問と回答のプログラムを作成することです。ユーザーが質問をすると、私が回答を生成します。私はこれまで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)
つまり、基本的には、1 回質問してから 1 回回答を返しますが、while ループに入ると、指定されたポイントでスタックします。少し助けます。ありがとうございました。