Daniel Oliveira
Daniel Oliveira

Reputation: 1290

Java try and catch until no exception is thrown

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.

Upvotes: 5

Views: 8674

Answers (2)

xiaofeng.li
xiaofeng.li

Reputation: 8587

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
    }
}

Upvotes: 14

shmosel
shmosel

Reputation: 50716

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
    }
}

Upvotes: 4

Related Questions