扫描程序错误,我无法弄清楚:NoSuchElementException

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

input = kb.nextInt(); 

堆栈跟踪:

线程“main”java.util.NoSuchElementException中的exception

在java.util.Scanner.throwFor(未知来源)

在java.util.Scanner.next(未知来源)

在java.util.Scanner.nextInt(未知来源)

在java.util.Scanner.nextInt(未知来源)

在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后,它会崩溃。它会正确保存文件,然后返回到循环的顶部,并在前面提到的行崩溃。 我希望它要求更多的输入。

是什么赋予了?

当我选择选项8时,在saveSurvey() ,它必须创建一个新的Scanner(在该方法中),因为所有这些都在我的main方法中。 这可能是问题吗?

是的,这可能是问题所在。 如果该Scanner具有与kb相同的源( System.in ?)并且是close() d,则关闭基础流,并且kb不再能够获得输入。

我想到了。

整个问题是由于我没有在main中创建静态扫描程序 – 当我在main之外的其他方法中需要它时,我创建了新的。

代替

 public class MainDriver { public static Scanner kb = new Scanner(System.in); public void main(String[] args) throws IOException { 

我有:

 public class MainDriver { public static void main(String[] args) throws IOException { public static Scanner kb = new Scanner(System.in); 

然后在其他方法中创建新的扫描仪。 在这些方法的最后,我关闭了扫描仪。 我猜它正在关闭本地扫描程序,因为当我摆脱其他方法中的所有close()语句时,问题就消失了。