Scanner Repeat Error

How to repeat the scanner when an exception occurs?
Consider this CLI application.

Example:

System.out.print("Define width: ");
    try {
        width = scanner.nextDouble();
    } catch (Exception e) {
        System.err.println("That not a number!");
        //width = scanner.nextDouble(); // Wrong code, this bring error.
    }

If the user does not enter type input double, then an error occurs. But I want an error message to appear. It should ask the user to enter the width again.

How to do it?

+5
source share
3 answers

If I understand you correctly, you want the program to ask the user to re-enter the correct input after the failure. In this case, you can do something like:

boolean inputOk = false;
while (!inputOk) {
    System.out.print("Define width: ");
    try {
        width = scanner.nextDouble();
        inputOk = true;
    } catch (InputMismatchException e) {
        System.err.println("That not a number!");
        scanner.nextLine();   // This discards input up to the 
                              // end of line
        // Alternative for Java 1.6 and later
        // scanner.reset();   
    }
}

: InputMismatchException. nextXxx , , .

+3

,

        Scanner in;
        double width;

          boolean inputOk = false;
          do
          {

               in=new Scanner(System.in);
              System.out.print("Define width: ");
                  try {
                      width = in.nextDouble();
                      System.out.println("Greetings, That a number!");
                      inputOk = true;
                  } catch (Exception e) {
                      System.out.println("That not a number!");
                      in.reset();

                  }
          }
          while(!inputOk);
    }
+1

You can use:

System.out.print("Define width: ");

boolean widthEntered = false;

// Repeath loop until width is entered properly
while (!widthEntered) {

    try {

        // Read width
        width = scanner.nextDouble();

        // If there is no exception until here, width is entered properly
        widthEntered = true;

    } catch (Exception e) {
        System.err.println("That not a number!");
    }
}
0
source

Source: https://habr.com/ru/post/1541951/


All Articles