I’m helping a friend with a java problem. However, we’ve hit a snag. We’re using Java.Util.Scanner.nextInt() to get a number from the user, asking continiously if the user gives anything else. Only problem is, we can’t figure out how to do the error handeling.
What we’ve tried:
do {
int reloop = 0;
try {
number = nextInt();
} catch (Exception e) {
System.out.println ("Please enter a number!");
reloop ++;
}
} while(reloop != 0);
Only problem is, this loops indefinatly if you enter in something not a number.
Any help?
You can use
hasNextInt()to verify that theScannerwill succeed if you do anextInt(). You can also call and discardnextLine()if you want to skip the “garbage”.So, something like this:
See also:
The problem with your code, in addition to the unnecessarily verbose error handling because you let
nextInt()throw anInputMismatchExceptioninstead of checking forhasNextInt(), is that when it does throw an exception, you don’t advance theScannerpast the problematic input! That’s why you get an infinite loop!You can call and discard the
nextLine()to fix this, but even better is if you use the exception-freehasNextInt()pre-check technique presented above instead.