Java tries and catch until an exception is thrown

I am trying to get an integer from a user using a scanner and an infinite loop. I know a solution to solve this problem, but I keep wondering why my first approach is not working 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 the “Invalid, try again” print on the screen forever.

+4
source share
2 answers

From Document API Scanner :

When the scanner throws an InputMismatchException, the scanner does not pass the token that caused the exception, so it can be retrieved or passed through some other method.

, , , ...

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

@LukeLee:

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

Source: https://habr.com/ru/post/1659678/


All Articles