java - 在 do while 循环中尝试 catch

标签 java exception try-catch do-while

程序要求用户输入 double num 1 和 double num 2 如果出现异常,我希望它再次询问 num 1 和 num 2 的输入

public static void main (String[] args) {
    Scanner sc = new Scanner(System.in);
    double num1, num2;
    int error = 0;
    int text;
    System.out.print("Enter 4 ");
        text = sc.nextInt();

    do{

        try{

    if(text == 4){
            System.out.print("Enter number 1: ");
            num1 = sc.nextDouble();
            System.out.print("Enter number 2: ");
            num2 = sc.nextDouble();
            double quotient = num1/num2;
            System.out.println("The Quotient of "+num1 + "/" +num2+ " = "+quotient);
            }
        }catch(Exception ex){ 
            System.out.println("You've entered wrong input");
                error = 1;
        }                                  

          }while(error == 1);
}

然后,当我尝试代码时,如果它会通过在 num1 或 num 2 中输入字符串来捕获异常,我就会遇到这个无限循环: 请输入数字1:您输入的内容有误 输入数字1:您输入错误 输入数字1:您输入错误 输入数字1:您输入错误 输入数字1:您输入错误

最佳答案

您需要重置循环内的error变量

do {
    error = 0;
    //...
} while(error == 1);

关于java - 在 do while 循环中尝试 catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45348919/

相关文章:

java - android pie 9.0 mobile:org.json.JSONException:类型为java.lang.String的值CLEARTEXT无法转换为JSONObject

c++ - 为什么在这个类中不调用析构函数

haskell - 将多个 IO 异常提取为一词多义

node.js - Node JS在一系列函数调用后未终止

java - 异常已被其他异常错误捕获

java - jOOQ - 如何使用 .whereNotExists() 进行条件更新?

java - 如何在 if 测试中正确使用 java 子字符串?

Javascript 异常隐藏在 Promises 中。我怎样才能在没有捕获的情况下显示它们?

java - try catch 异常 while 循环

java gdb 运行时