2

所以我的第一个任务是制作一个简单的问答程序。用户提出问题,我生成答案。我以前从未做过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 循环中调用 this 的函数如下:

    //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 循环时,它会卡在指定的点。帮助不大。谢谢你。

4

1 回答 1

4

我注意到一件事:您可能不应该调用close()扫描仪。根据JavaDocs ,您正在关闭底层输入流(标准输入) 。

于 2012-08-30T15:28:49.077 回答