2014-10-10 37 views
0

相关的代码段:什么会导致扫描程序从方法调用返回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();线。

+1

在每个循环迭代中创建一个新的扫描器的任何一点?尝试在循环之外移动它。 – 2014-10-10 08:32:20

+0

试图将它移动到主体的顶部,但我得到了指向同一行的完全相同的错误 – Spork 2014-10-10 08:35:38

+2

@Spork是否可以发布完整的代码? – arin1405 2014-10-10 08:42:02

回答

0

@Spork
Scanner kbd = new Scanner(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 
    } 
} 

让我知道它是否有帮助。

相关问题