Query about using try catch in java. Netbeans

0
public static void main(String[] args) {
    Scanner entrada = new Scanner(System.in);

    int edad;

    boolean repetir = true;

    while (repetir) {
        System.out.println("introduce edad");

        try {
            edad = entrada.nextInt();
            repetir = false;
        } catch (InputMismatchException e) {
            entrada.nextLine();//Si quito esta linea entra en un bucle infinito.. Por qué? No entiendo porque se pone este codigo
            System.out.println("error");
        }
    }
}

Why is this code put in the catch? input.nextLine ();

Why does it go into an infinite loop if I remove it?

    
asked by Agustin Ozuna Leguizamón 04.05.2018 в 03:44
source

1 answer

0

That line allows the user to enter the program again a line of text. The exception InputMismatchException is thrown when the scanner receives an input value that does not wait.

Without this part the program would enter an infinite loop because the condition for repeating the loop while is always true . In other words, because the variable repetir is initialized with true and you never make it change its value, therefore the loop while will continue repeating.

public static void main(String[] args) {
    Scanner entrada = new Scanner(System.in);

    int edad;

    boolean repetir = true;

    while (repetir) {
        System.out.println("introduce edad");

        try {
            edad = entrada.nextInt();
            repetir = false;
        } catch (InputMismatchException e) {
            repetir = false();
            // Ya puedes eliminar la línea que iba aquí.
            System.out.println("error");
        }
    }
}

If you do this you can end the loop when it finds an error and has entered the catch block. With the previous code you can delete the line that forces the user to enter the keyboard.

    
answered by 04.05.2018 / 04:09
source