【问题标题】:do while trouble with try catch enclosed尝试捕获问题时做
【发布时间】:2015-07-11 02:26:15
【问题描述】:

我正在尝试让我的 do while 块正确运行。封闭在其中的是一个 try and catch 块,它只是部分工作。我希望它在输入除 Int 以外的内容时捕获异常(InputMismatchException),并在除以零时捕获异常。如果任何一个捕获发生,那么目的是它通过 do while 循环再次返回尝试。目前,它适用于ArithmeticException,但不适用于InputMismatchException。当我输入字符而不是 Int 时,它似乎不停地循环。请帮忙。我不明白为什么一个有效,另一个无效。

    int div;
    boolean check = true;

    while (check) {
        boolean result = true;
        do {
            try {
                System.out.println("The following operation will divide the first number by the second.");
                System.out.println("Enter first number.");
                example.a = user_input.nextInt();
                System.out.println("Enter second number.");
                example.b = user_input.nextInt();

                div = example.div();
                System.out.println("The result of this division is " + div);
                result = true;
            } catch (InputMismatchException e) {
                System.out.println("That is not a number. Please try again.");
                result = false;
            } catch (ArithmeticException e) {
                System.out.println("Division by zero.");
                result = false;
            }
        } while (result = true);

【问题讨论】:

    标签: java


    【解决方案1】:
    while (result = true)
    

    应该是

    while (result == true)
    

    或者只是

    while (result)
    

    【讨论】:

      【解决方案2】:

      获取InputMismatchException 不会跳过错误数据,因此对nextInt() 的下一次调用将因同样的原因而失败。你应该尝试在你的捕获中调用nextLine()

      } catch (InputMismatchException e) {
          System.out.println("That is not a number. Please try again.");
          result = false;
          user_input.nextLine(); // Advance past the bad stuff
      }
      

      【讨论】:

        【解决方案3】:

        删除你的do,只使用一个while循环

        并将你的第二个 while 更改为

        while(result)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多