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?
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();
}
}
Don't call
eingabeMove.close();
at the end of thatwhile
loop. You're causing the Scanner to become inoperable at the end of the first loop.Since the loop always terminates with a
return
, it doesn't make sense to close the Scanner in thisschleife()
method.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 leteingabeMove
go out of scope when theschleife()
returns.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.Calling code: