有 Java 编程相关的问题?

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

java TryCatch异常处理未提供正确的响应

我不知道为什么当我输入除整数值以外的任何东西时,输出没有显示Invalid Format!

这就是我试图实现的异常处理。另外,如何在不引起无限循环的情况下关闭finally子句中的Scanner

class ConsoleInput {

public static int getValidatedInteger(int i, int j) {
    Scanner scr = new Scanner(System.in);
    int numInt = 0;

    while (numInt < i || numInt > j) {
        try {
            System.out.print("Please input an integer between 4 and 19 inclusive: ");
            numInt = scr.nextInt();

            if (numInt < i || numInt > j) {
                throw new Exception("Invalid Range!");
            } else {
                throw new InputMismatchException("Invalid Format!");
            }

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            scr.next();

        }

    }
    scr.close();
    return numInt;
}

这是我想要得到的结果:


共 (2) 个答案

  1. # 1 楼答案

    在异常捕获块和添加scr之前,您需要在单独的捕获块中捕获InputMismatchException。next();例如:

    public static int getValidatedInteger(int i, int j) {
        Scanner scr = new Scanner(System.in);
        int numInt = 0;
    
        while (numInt < i || numInt > j) {
            try {
                System.out.print("Please input an integer between 4 and 19 inclusive: ");
                numInt = scr.nextInt();
    
                if (numInt < i || numInt > j) {
                    throw new Exception("Invalid Range!");
                }
            } catch (InputMismatchException ex) {
                System.out.println("Invalid Format!");
                scr.next();
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
                scr.next();
    
            }
    
        }
        scr.close();
        return numInt;
    }
    
  2. # 2 楼答案

    如果输入的不是int,则会在以下行抛出错误:

     numInt = scr.nextInt();
    

    然后陷入catch块,从而跳过print语句。您需要检查是否存在下一个int:

    if(!scr.hasNextInt()) {
       throw new InputMismatchException("Invalid Format!");
    }
    

    Also, how can I close the Scanner in a finally clause without causing an infinite loop.

    不需要在finally块中关闭Scanner。事实上,你根本不应该关上它。关闭System.in是不好的做法。一般来说,如果没有打开资源,就不应该关闭它