Treatment of exceptions within a loop

0

I intend to read two whole numbers while the two data read are not correct. That is, if in any of the two data something that is not an integer is introduced, the do-while loop is repeated again. Next I leave the code:

int a = 0, b = 0;

boolean est;

Scanner sc = new Scanner(System.in);

do {

    try {
        est = false;
        System.out.print("Introduce el primer numero a: ");
        a = sc.nextInt();
        System.out.print("Introduce el segundo numero b: ");
        b = sc.nextInt();

    } catch (InputMismatchException exc) {

        System.out.println("Error, lo introducido no es valido: " + exc.getMessage());
        est = true;
    }

} while(est);

The fact is that when you enter something that is not an integer, the loop repeats indefinitely. Where is the problem?

Thanks in advance.

    
asked by Psg 18.10.2017 в 11:44
source

2 answers

-1

From the documentation of Scanner.nextInt :

  

Scans the next token of the input as an int. This method will throw   InputMismatchException if the next token can not be translated into a   valid int value as described below. If the translation is successful,   the scanner advances past the input that matched .

nextInt, if you can not process the token, throw an exception, but do not go to the next token. You have to do it in block catch , for example with sc.next() , ignoring the result of that call.

    
answered by 18.10.2017 / 12:03
source
4

What I recommend is that you do the following:

Instead of reading the following Int , better read the following next and try to parse it to Int :

a = Integer.parseInt(sc.next());

With this you also try to capture the error NumberFormatException :

catch (final NumberFormatException asd)

and you can put the same as you have in the previous catch if you like it or handle it in another way.

    
answered by 18.10.2017 в 12:09