Error control, it generates infinite loop

1

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);

}
    
asked by AnnaPS 18.01.2017 в 12:52
source

2 answers

2

You are not cleaning the incorrectly entered number, so you will always try again to get what you entered the first time.

To clean the invalid data you must read a complete line:

public static void main(String[] args) {
  int num;

  Scanner pedir = new Scanner(System.in);
  while (true) {
    System.out.print("Inserte un numero: ");
    try {
      num = pedir.nextInt();
      System.out.println("El valor es " + num);
      break;
    } catch (InputMismatchException e) {
      /* Limpiamos la entrada incorrecta */
      pedir.next();
      System.out.println("Lo siento, has introducido letras");
    } catch (NoSuchElementException e) {
      /* Nunca se captura, ver:
      https://docs.oracle.com/javase/7/docs/api/java/lang/RuntimeException.html */
      System.out.println("Fin de la entrada de datos");
      break;
    }
  }
}

That should be enough, but keep in mind that you should check if the field with hasNextInt() is valid instead of try/catch :

public static void main(String[] args) {
  int num;

  Scanner pedir = new Scanner(System.in);
  while (true) {
    System.out.print("Inserte un numero: ");
    /* Comprobamos si quedan más datos en la entrada estándar */
    if (pedir.hasNext()) {
      if (pedir.hasNextInt()) {
        num = pedir.nextInt();
        System.out.println("El valor es " + num);
        break;
      } else {
        /* Limpiamos la entrada incorrecta */
        pedir.next();
        System.out.println("Lo siento, has introducido letras");
      }
    } else {
      System.out.println("Fin de la entrada de datos");
      break;
    }
  }
}
    
answered by 18.01.2017 / 13:22
source
3

You just have to add pedir.next() in error handling:

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 ");
            pedir.next();
        }
    }while(error);

}
    
answered by 18.01.2017 в 13:15