!Good!
I'm trying (in a very simple code) that when the user writes a letter or word in a variable that expects a numeric type , catch the error with a try catch
and repeat to the user to enter some number.
For example, as in this code, to serve as an explanation...
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numero1;
int numero2;
int total;
do {
try {
System.out.print("Introduce numero 1: ");
numero1 = sc.nextInt();
System.out.print("Introduce numero 2: ");
numero2 = sc.nextInt();
} catch (Exception ex) {
System.out.println("No es un numero. Toma como valor 0. Repite");
numero1 = 0;
numero2 = 0;
}
total = numero1 + numero2;
System.out.println("Total: " + total);
} while (total <= 0);
}
}
My idea is that when entering a non-numeric data , it collects the error and, in this case, prints a message and gives both variables a value: 0 . For so, the total is equal to 0 , and the loop is activated.
But with this example it becomes an infinite loop, and I'm not understanding why, nor how to do what I want.
I would like to know if the way I want to solve it is possible, or if there is any alternative...
All the best :)
The problem you have is that when the user enters non-numeric data, the error occurs, but the same data remains in the buffer of the
Scanner
, waiting to be read. Upon catching the error, the execution returns to the beginning, but the Scanner is still in the same position, so the next call tonextInt()
fails again, and remains in an infinite loop.You can, within your exception handler, call
nextLine();
delScanner
to ignore whatever the user entered on that line and start again, something like:With that, your program will return to the execution you expect.