是什么导致Scanner在从方法调用返回while循环时抛出NoSuchElementException



代码的相关部分:

Scanner kbd = new Scanner(System.in); //to get user input
while(!close) { //program will keep prompting user for selection until they close it
    System.out.println(menu); //prints the menu
    selection = kbd.nextLine(); //gets the menu selection from the user

只有当从方法调用返回while循环时才会发生这种情况,如果我从没有方法调用的if语句返回,则不会发生错误。以下是完整的错误消息:

Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at class.main(class.java:29)

它指向的线是selection = kbd.nextLine();线。

我在这里找到了问题的解决方案!

Java扫描仪获取输入,调用一个方法,然后返回读取更多不工作的输入

事实证明,在我的方法中,扫描仪的其他实例主要导致了扫描仪的问题。将扫描仪移到班级的顶部解决了这个问题!

@Spork
扫描仪kbd=新扫描仪(System.in)//获取用户输入

while(!close) { //program will keep prompting user for selection until they close it
  System.out.println(menu); //prints the menu
  if(kbd.hasNextLine(){
      selection = kbd.nextLine(); //gets the menu selection from the user
  }
}

如果有帮助,请告诉我。

最新更新