【问题标题】:Validating input with try-catch使用 try-catch 验证输入
【发布时间】:2017-04-05 01:48:40
【问题描述】:

我正在尝试学习 try-catch 的用法,并且必须验证输入,以便用户必须输入 1 或 2 才能继续程序。我相信我已经接近了,但如果用户输入错误的内容,例如“3”或“2.12”,似乎无法让程序继续运行。

这是我所拥有的:

String input = " ";

try {

        Scanner scan = new Scanner(System.in);
        input = scan.next();

        Integer.parseInt(input);

        if (!input.equals("1") && !input.equals("2")) {

            System.out.println();
            System.out.println("Invalid imput! Please select '1' or '2':");
        }

    } catch (InputMismatchException a) {

        System.out.println();
        System.out.println("Invalid imput! Please select '1' or '2':");

    }

【问题讨论】:

  • if (!input.equals("1") && !input.equals("2")) { throw new InputMismatchException ();
  • 当来自扫描仪的输入不同于预期的类型(不是值)时,您会抛出 InputMismatchException。为你的 scnerio 抛出 InputMismatchException 是在滥用它。

标签: java try-catch


【解决方案1】:

我不一定看到在您的用例中使用 InputMismatchException 的意义。相反,如果输入与您的预期不符,您可以记录错误并提示用户再次输入。

[Integer#parseInt()][1] 可以在输入不是实际整数时抛出异常。在您的原始代码中,您实际上从未使用过此调用的结果,但我在回答中已经这样做了。在这种情况下,使用 try-catch 块可能确实有意义。

int result;
while (true) {
    try {
        Scanner scan = new Scanner(System.in);
        input = scan.next();
        result = Integer.parseInt(input);
    } catch(Exception e) {
        System.out.println("Could not parse input, please try again.");
        continue;
    }

    if (result != 1 && result != 2) {
        System.out.println("Invalid input! Please select '1' or '2':");
    }
    else {
        break;
    }
}

【讨论】:

    【解决方案2】:

    你应该在你的条件中加入 throw 语句,以便你的 catch 语句获取错误,代码应该是这样的:

    String input = " ";
    
    try {
    
        Scanner scan = new Scanner(System.in);
        input = scan.next();
    
        Integer.parseInt(input);
    
        if (!input.equals("1") && !input.equals("2")) {
    
            System.out.println();
            System.out.println("Invalid imput! Please select '1' or '2':");
            throw new InputMismatchException ();
        }
    
    } catch (InputMismatchException a) {
    
        System.out.println();
        System.out.println("Invalid imput! Please select '1' or '2':");
    
    
    }
    

    【讨论】:

    • 这有帮助,但它不能保持程序运行?
    • 尝试在System.out.println("输入无效!请选择'1'或'2':")之后添加(input = scan.next(););在 catch 语句中
    【解决方案3】:

    代码需要正整数,但可以输入字符串并再次循环,直到得到正整数输入值。

    Scanner scanner = new Scanner(System.in);
    Integer expectedOutput = -1;
    
    public Integer getInputNumber(){
    
        boolean valid;
        String inputData;
    
        do {
            System.out.print("Enter Input Number: \t");
            try {
                inputData = scanner.nextLine();
                // expecting positive integers
                if (Integer.parseInt(inputData) > 0) {
                    expectedOutput = Integer.parseInt(inputData);
                    valid = true;
                } else {
                    System.out.println("Invalid Input!");
                    valid = false;
                }
            } catch (Exception ex){
                valid = false;
            }
        } while(!valid);
        return expectedOutput;}
    

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      • 1970-01-01
      • 2023-01-31
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      相关资源
      最近更新 更多