One of my final project requirements is that, if it is console based which mine is, entering ctrl + z WON'T mess up the program. The nextLine() statement from my scanner is within a while loop, and when I try to catch the NoSuchElementException from entering ctrl+z, the error message in the catch block loops endlessly.
while (!advanceTurn) {
System.out.print("\nCommand: ");
try {input = s.nextLine();}
catch (NoSuchElementException e) {
System.out.println("Use the EXIT command to exit the game.");
s = new Scanner(System.in);
input = "asdfjkl;";
continue;
}
System.out.println();
// This takes the input and decides what command was entered (if any) and deals
// with it appropriately.
parseCommand(input);
}
As you can see in the code, I've tried to re-initialize the scanner when the error is caught, and then jump back to the beginning of the loop so a new line can be grabbed, but it appears that the error still persists even when there's no new input from the keyboard, so I'm pretty much stumped as to how to solve this. Any help is appreciated, thanks.
EDIT: I'm using Eclipse IDE if that helps.
I talked with my instructor today and we fixed the problem by jumping outside of the while loop with a return statement in the catch block, and then initializing s as a new scanner just before entering the loop again. Since the purpose of this snippet is to repeatedly get commands until certain commands that constitute the end of a turn are entered, the while loop is entered every time a command is be entered, and it now works just fine for me.