Scanner Exception Retry

2019-06-21 05:03发布

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?

3条回答
相关推荐>>
2楼-- · 2019-06-21 05:22

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 (Exception e) {
            System.err.println("That's not a number!");
            scanner.next(); // here is to re-enter it.
        }
}
查看更多
够拽才男人
3楼-- · 2019-06-21 05:37

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);
    }
查看更多
爷、活的狠高调
4楼-- · 2019-06-21 05:38

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's not a number!");
    }
}
查看更多
登录 后发表回答