Scanner Exception Retry

佐手、 提交于 2019-11-29 14:08:53
Pablo Francisco Pérez Hidalgo

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.

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);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!