Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java try and catch until no exception is thrown

Tags:

java

exception

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.

like image 835
Daniel Oliveira Avatar asked Nov 03 '16 01:11

Daniel Oliveira


2 Answers

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
    }
}
like image 58
xiaofeng.li Avatar answered Sep 28 '22 18:09

xiaofeng.li


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
    }
}
like image 43
shmosel Avatar answered Sep 28 '22 18:09

shmosel