Java新手。在while循环中使用scanner类时出错?

时间:2012-08-30 15:23:19

标签: java io

所以我的第一个任务是制作一个简单的问答程序。用户提出问题,然后我会生成一个答案。我以前从未做过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循环时,它会卡在指定的点上。 没什么帮助。谢谢。

1 个答案:

答案 0 :(得分:4)

我注意到的一件事:您可能不应该在扫描仪上拨打close()。您正在关闭基础输入流(标准输入),根据JavaDocs