I am trying to get an integer from the user using a Scanner and an infinite loop. I know a solution to solve this problem but I keep wondering why doesn't my first approach work properly?
Scanner myScanner = new Scanner(System.in);
int x = 0;
while(true){
try{
System.out.println("Insert a number: ");
x = myScanner.nextInt();
break;
}catch(InputMismatchException e){
System.out.println("Invalid, try again.");
continue;
}
}
It works on the first iteration but then it just keeps printing "Invalid, try again" on the screen forever.
From the Scanner API doc:
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
So the invalid token is still there, causing another exception and another and another...
Scanner myScanner = new Scanner(System.in);
int x = 0;
while(true){
try{
System.out.println("Insert a number: ");
x = myScanner.nextInt();
break;
}catch(InputMismatchException e){
System.out.println("Invalid, try again.");
myScanner.next(); // skip the invalid token
// continue; is not required
}
}
An alternative to @LukeLee's solution:
Scanner myScanner = new Scanner(System.in);
int x = 0;
while(true){
try{
System.out.println("Insert a number: ");
x = Integer.parseInt(myScanner.next());
break;
}catch(NumberFormatException e){
System.out.println("Invalid, try again.");
// continue is redundant
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With