This question already has an answer here:
这个问题在这里已有答案:
- Scanner throws NoSuchElementException on nextInt 2 answers
Scanner在nextInt 2答案上抛出NoSuchElementException
The first time menu() is displayed, I'm able to enter input and runGame() works. The second time the menu is displayed, the program is crashing on the line int answer = scanner.nextInt() with a java.util.NoSuchElementException. It seems that there isn't a 'nextInt' to read in, but I don't ever have the chance to enter it the second time.
第一次显示菜单(),我可以输入输入和runGame()工作。第二次显示菜单时,程序在使用java.util.NoSuchElementException的行回答int answer = scanner.nextInt()时崩溃。似乎没有'nextInt'可以阅读,但我没有机会第二次进入它。
public void runGame(){
int userPick = 0;
userPick = menu();
while (userPick != 10){ //user exists with a choice of 10
switch (userPick){
case 1:
System.out.println("User picked 1");
break;
case 2:
...
default:
...
}
userPick = menu();
}
public int menu(){
Scanner scanner = new Scanner(System.in);
System.out.println("Please choose an integer from 0 - 10(quit)");
int answer = scanner.nextInt();
scanner.close();
return answer;
}
1 个解决方案
#1
1
Per, Scanner throws NoSuchElementException on nextInt
Per,Scanner在nextInt上抛出NoSuchElementException
When you call scanner.close() it closes your underlying stream, which is System.in; once you close System.in the only way to get it back is to restart your program.
当你调用scanner.close()时,它会关闭你的底层流,即System.in;一旦你关闭System.in唯一的方法来恢复它是重新启动你的程序。
Removing the close took care of the issue.
删除关闭处理问题。
#1
1
Per, Scanner throws NoSuchElementException on nextInt
Per,Scanner在nextInt上抛出NoSuchElementException
When you call scanner.close() it closes your underlying stream, which is System.in; once you close System.in the only way to get it back is to restart your program.
当你调用scanner.close()时,它会关闭你的底层流,即System.in;一旦你关闭System.in唯一的方法来恢复它是重新启动你的程序。
Removing the close took care of the issue.
删除关闭处理问题。