程序要求用户输入 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/