Java - entrada del usuario - bucle en caso de error

Aquí está mi código Java:

Scanner userInput = new Scanner(System.in);
while (true) { // forever loop
    try {
        System.out.print("Please type a value: "); // asks user for input
        double n = userInput.nextDouble(); // gets user input as a double
        break; // ends if no error
    }
    catch (Throwable t) { // on error
        System.out.println("NaN"); // not a number
    }
}

You can see what this is supposed to do from the comments.

But when I enter in something that's not a number, this happens:

Please type a value: abc
NaN
Please type a value: NaN
Please type a value: NaN
Please type a value: NaN
Please type a value: NaN
Please type a value: NaN
Please type a value: NaN

and so on until I force stop it.

In Python I would just do this:

while True:
    try:
        n = float(raw_input("Please type a value: "))
        break
    except Exception:
        print "NaN"

How do I do this in Java? I've tried using a do while.

preguntado el 05 de septiembre de 12 a las 10:09

No atrapar Throwable pero lo especifico InputMismatchException. -

Aside: in Python you should probably use ValueError más bien que Exception. -

4 Respuestas

Call the línea siguiente() método en catch bloquear.

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

 catch (InputMismatchException t) { // on error
    userInput.nextLine();
    System.out.println("NaN"); // not a number
  }

Respondido el 05 de Septiembre de 12 a las 11:09

while (true) { // forever loop
    try {
        scanner userInput = new Scanner(System.in); 
        System.out.print("Please type a value: "); // asks user for input
        double n = userInput.nextDouble(); // gets user input as a double
        break; // ends if no error
    }
    catch (Throwable t) { // on error
        System.out.println("NaN"); // not a number
    }
}

you should use scanner class inside the while loop then only it will ask next input value if the given input value is wrong.

Respondido el 05 de Septiembre de 12 a las 11:09

Prueba esto,

double n;
boolean is_valid;

do {
    try {
        System.out.print("Please type a value: ");
        Scanner kbd = new Scanner(System.in);
        n = kbd.nextDouble();
        is_valid = true;
    } catch (Exception e) {
        System.out.println("NaN"); 
        is_valid = false;
    }
} 
while (!is_valid);

Respondido el 05 de Septiembre de 12 a las 11:09

As above , You can change it like this:

    Scanner userInput = new Scanner(System.in);
    while (true) { // forever loop
        try {
            System.out.print("Please type a value: "); // asks user for input
            double n = userInput.nextDouble(); // gets user input as a double
            break; // ends if no error
        }
        catch (Throwable t) { // on error
            System.out.println("NaN"); // not a number
            userInput.nextLine();
        }
    }

Respondido el 05 de Septiembre de 12 a las 11:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.