提问人:roshannepal_x 提问时间:5/12/2022 更新时间:5/12/2022 访问量:46
如何解决Java扫描仪中的NoSuchElementException错误?[复制]
how to solve NoSuchElementException Error in Scanner of Java? [duplicate]
问:
我正在制作一个简单的主机游戏,允许玩家进入
x,-x,y,-y方向,根据从键盘收集的输入分别为a,d,w和s,
但是扫描仪正在抛出,我也尝试收集数据,但我得到了类似的异常。
注意:但是扫描仪只能工作一次,即第一次。String
NoSuchElementException
nextInt()
我的代码
private static void gamePlay(boolean isPlaying) {
while (isPlaying) {
System.out.println("Choose a, d , s or w for movement:");
Scanner sc = new Scanner(System.in);
String choice = sc.next();
sc.close();
// code for movement of player according to a or s or d or w
switch (choice) {
case "a":
// Some code here
// move -x
break;
case "d":
// Some code here
// move +x
break;
case "w":
// Some code here
// move +y
break;
case "s":
// Some code here
// move -y
break;
case "q":
//quit
isPlaying = false;
break;
default:
break;
}
}
}
**输出**
Choose a, d , s or w for movement:
a
Choose a, d , s or w for movement:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at App.gamePlay(App.java:37)
at App.main(App.java:17)
答:
0赞
rlowell
5/12/2022
#1
private static void gamePlay(boolean isPlaying) {
while (isPlaying) {
System.out.println("Choose a, d , s or w for movement:");
Scanner sc = new Scanner(System.in);
String choice = sc.next();
// code for movement of player according to a or s or d or w
switch (choice) {
case "a":
// Some code here
// move -x
break;
case "d":
// Some code here
// move +x
break;
case "w":
// Some code here
// move +y
break;
case "s":
// Some code here
// move -y
break;
case "q":
//quit
sc.close();
isPlaying = false;
break;
default:
break;
}
}
}
评论
close()
Scanner
System.in
Scanner
System.in
Scanner