java - 刚接触java。在 while 循环中使用扫描仪类时出错?

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

最佳答案

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

关于java - 刚接触java。在 while 循环中使用扫描仪类时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12200299/

相关文章:

java - 在 ExecutorService 中使用同步块(synchronized block)

java - Elasticsearch - 从 json 文件加载 ILM 策略

io - 尽管数据集上有多线程设置,TF 时间线仍显示串行执行

java - 你能解释一下这个 Java HashMap 键冲突吗?

java - 静态引用

java - 在 foreach 循环中直接转换

linux - IN 指令段错误,内联汇编 GCC

python - 读取所有子目录中的wav文件

c - 如何从 printf 获取整数的空白输出

创建多个文件并且每个文件都打印完全相同的东西--C