java - 我无法弄清楚的扫描仪错误 : NoSuchElementException

标签 java exception java.util.scanner

它在 do-while 循环内的第三行崩溃,并且不等待我的输入:

 input = kb.nextInt();

堆栈跟踪:

Exception in thread "main" java.util.NoSuchElementException

at java.util.Scanner.throwFor(Unknown Source)

at java.util.Scanner.next(Unknown Source)

at java.util.Scanner.nextInt(Unknown Source)

at java.util.Scanner.nextInt(Unknown Source)

at main.MainDriver.main(MainDriver.java:50)

相关代码:

do
    {
        displayFullMenu();
        System.out.print("Selection: ");
        input = kb.nextInt();
        
        switch (input)
        {
        //Create new survey
        case 1:     currentSurvey = new Survey();
                    break;
        
        //Display current survey            
        case 2:     currentSurvey.display();
                    break;
        
        //Save current survey           
        case 3:     saveSurvey(currentSurvey);
                    break;
                    
        //Load a survey
        case 4:     currentSurvey = loadSurvey();
                    break;
        
        //Modify a survey
        case 5:     currentSurvey.modify();
                    break;
                    
        /*******************Test Functions*******************/
                    
        //Create new test
        case 6:     currentSurvey = new Test();
                    break;
        
        //Display current test
        case 7:     currentSurvey.display();
                    break;
        
        //Save current test
        case 8:     saveSurvey(currentSurvey);
                    break;
                    
        //Load a test
        case 9:     currentSurvey = loadTest();
                    break;
                    
        //Modify a test
        case 10:    currentSurvey.modify();
                    
        default:    System.out.println("Invalid choice. Please make a valid choice: ");
                    input = kb.nextInt();
                    System.out.println();
        }
    } while (input != 99);
    kb.close();

在我选择选项 9 后它崩溃了。它正确地保存了文件,然后返回到循环的顶部,并在前面提到的那一行崩溃了。我希望它要求更多输入。

什么给了?

最佳答案

When I choose option 8, in saveSurvey(), it has to create a new Scanner (in that method) because all of this is inside my main method. Could that be the issue?

是的,这可能是问题所在。如果 Scannerkb 具有相同的源 (System.in?) 并且是 close()d,关闭底层流,kb 无法再获取输入。

关于java - 我无法弄清楚的扫描仪错误 : NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13223723/

相关文章:

java - 如何在 snakeyaml 中隐藏 bean 类型

c# - IDictionary w/Null Key - MSDN 拼写错误或其他问题?

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

java - 从java中的数组中查找重复元素出现两次以上

java - 如何找出 Eclipse 卡住的原因?

java - 在java中通过静态方法访问私有(private)变量

java - 如何将通用对象发布到 Spring Controller ?

java - 处理Java中的几个异常

java - 如何在java.util.Scanner中匹配两个或多个空格?

java - 为什么我不能在使用scanner.close()后创建另一个扫描仪对象?