简体   繁体   English

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

[英]New to java. Error using scanner class in while loop?

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. 我从来没有做过Java。 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: 在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);

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. 所以基本上,发生的事情是,它先问一个问题,然后又给出一次答案,但是当它进入while循环时,它停留在指示的位置。 Little help. 没什么帮助。 Thank you. 谢谢。

One thing that I noticed: you should probably not call close() on the scanner. 我注意到的一件事:您可能不应该在扫描仪上调用close() You're closing the underlying input stream (standard input), according to the JavaDocs . 根据JavaDocs ,您正在关闭基础输入流(标准输入)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM