有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java扫描程序异常重试

发生异常时如何使扫描仪重试
考虑这个应用程序在CLI模式下运行。

例如:

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.
    }

如果用户没有输入double类型的输入,则抛出错误。但我想在出现错误消息之后。它应该要求用户再次输入宽度

怎么做


共 (2) 个答案

  1. # 1 楼答案

    如果我理解正确,您希望程序在失败后要求用户重新输入正确的输入。在这种情况下,您可以执行以下操作:

    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();   
        }
    }
    

    注意:您应该只捕获并重试一次^{nextXxx方法会抛出其他异常,如果您尝试重试这些异常,您的应用程序将进入无限循环

  2. # 2 楼答案

    这个很好用,我仔细检查过了

            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);
        }