my question is short and sweet. I do not understand why my program infinitely loops when catching an error. I made a fresh try-catch statement but it looped and even copied
Your program runs forever because calling nextInt
without changing the state of the scanner is going to cause an exception again and again: if the user did not enter an int
, calling keyboard.nextInt()
will not change what the scanner is looking at, so when you call keyboard.nextInt()
in the next iteration, you'll get an exception.
You need to add some code to read the garbage the user entered after servicing an exception to fix this problem:
try {
...
} catch(Exception e) {
System.out.println("Error: invalid input:" + e.getMessage());
again = true;
keyboard.next(); // Ignore whatever is entered
}
Note: you do not need to rely on exceptions in this situation: rather than calling nextInt()
, you could call hasNextInt(), and check if the scanner is looking at an integer or not.