Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanner Exception Retry

How to make scanner retry when exception occur?
Consider this app running on CLI mode.

Example:

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

If the user not inputting double type input, then the error thrown. But i want after the error message appears. It's should be asking the user input the width again.

How to do that?

like image 387
GusDeCooL Avatar asked Oct 01 '22 17:10

GusDeCooL


2 Answers

If I understood you correctly, you want the program to ask the user to re-enter a right input after it fails. In that 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's not a number!");
        scanner.nextLine();   // This discards input up to the 
                              // end of line
        // Alternative for Java 1.6 and later
        // scanner.reset();   
    }
}

Note: you should only catch and retry for a InputMismatchException. The nextXxx methods throw other exceptions, and if you attempt to retry those, your application will go into an infinite loop.

like image 187
Pablo Francisco Pérez Hidalgo Avatar answered Oct 03 '22 06:10

Pablo Francisco Pérez Hidalgo


This works perfectly,i have double checked

        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's a number!");
                      inputOk = true;
                  } catch (Exception e) {
                      System.out.println("That's not a number!");
                      in.reset();

                  }
          }
          while(!inputOk);
    }
like image 38
user3662273 Avatar answered Oct 03 '22 05:10

user3662273