I am starting to use try-catch
. In this example I ask for a number and if the user enters a number it is displayed, if he writes any letter the error jumps.
My intention was that when I entered a letter I would miss the message of "Lo siento, has introducido letras"
, and that I would ask for the number again. The problem is that it shows me the message of "Lo siento..."
infinitely.
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int num;
boolean error;
Scanner pedir = new Scanner(System.in);
do {
try {
System.out.print("Inserte un numero: ");
num = pedir.nextInt();
System.out.println("El valor es " + num);
error=false;
} catch (InputMismatchException e) {
error=true;
System.out.println("Lo siento has introducido letras ");
}
}while(error);
}