java.lang.IllegalStateException:扫描仪关闭
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28052519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.lang.IllegalStateException: Scanner closed
提问by kellerprogger
I got the following code, but after the first loop, my debugger is giving following errors,it s strange, i did it all the time like that, but it doesnt work anymore, this is pretty strange?! I checked it step-by-step, it is just stoppen after the switch order?
我得到了以下代码,但是在第一个循环之后,我的调试器给出了以下错误,很奇怪,我一直都是这样做的,但它不再起作用了,这很奇怪吗?!我一步步查了一下,switch命令后就停止了?
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Unknown Source)
at java.util.Scanner.findWithinHorizon(Unknown Source)
at java.util.Scanner.nextLine(Unknown Source)
at Level.schleife(Level.java:35)
at Crawler.main(Crawler.java:23)
public boolean schleife() {
System.out.println("Das Spiel beginnt, bewege Dich mit der WASD Steuerung!");
Scanner eingabeMove = new Scanner(System.in);
tmpi = positioni;
tmpj = positionj;
while (true) {
String bewegung = eingabeMove.nextLine();
switch (bewegung) {
case "w": { // vorw?rts
tmpi += 1;
if (actionResult()) {
positioni = tmpi;
break;
} else {
return false;
}
}
case "a": { // links
tmpj -= 1;
if (actionResult()) {
positionj = tmpj;
break;
} else {
return false;
}
}
case "s": { // rückw?rts
tmpi -= 1;
if (actionResult()) {
positioni = tmpi;
break;
} else {
return false;
}
}
case "d": { // rechts
tmpj += 1;
if (actionResult()) {
positionj = tmpj;
break;
} else {
return false;
}
}
default: { // falsche Eingabe
System.out.println("Falsche Eingabe!");
continue;
}
}
eingabeMove.close();
}
}
回答by gknicker
Don't call eingabeMove.close();
at the end of that while
loop. You're causing the Scanner to become inoperable at the end of the first loop.
不要eingabeMove.close();
在while
循环结束时调用。您导致扫描仪在第一个循环结束时无法运行。
Since the loop always terminates with a return
, it doesn't make sense to close the Scanner in this schleife()
method.
由于循环总是以 a 终止return
,因此在此schleife()
方法中关闭 Scanner 没有意义。
You actually don't need to close the Scanner though, because it wraps System.in
which never closes anyhow. Given this fact, you can simply let eingabeMove
go out of scope when the schleife()
returns.
不过,您实际上不需要关闭 Scanner,因为它System.in
无论如何都不会关闭。鉴于这一事实,您可以eingabeMove
在schleife()
返回时简单地放手超出范围。
If you really want to close the Scanner, you should pass eingabeMove
as a parameter to the method, and close it from the calling method.
如果你真的想关闭扫描器,你应该将它eingabeMove
作为参数传递给方法,并从调用方法中关闭它。
public boolean schleife(Scanner eingabeMove) {
// use the scanner
}
Calling code:
调用代码:
Scanner eingabeMove = new Scanner(System.in);
schleife(eingabeMove);
eingabeMove.close();