尝试抓住一个循环 [英] try catch in a do while loop
问题描述
程序要求用户输入double num 1和double num 2
,如果有异常,我希望它再次询问num 1和num 2的输入
The program asks for the user input for the double num 1 and double num 2 and if there is an exception I want it to ask again for the input of num 1 and 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或num2我有这个无限循环:
输入数字1:输入错误的输入
输入数字1:输入错误输入
输入编号1:输入错误输入
输入编号1:输入错误输入
输入编号1:输入错误输入
then when I try the code if it will catch the exceptions by inputing string in the num1 or num 2 I'm having this infinite loop :
Enter number 1: You've entered wrong input
Enter number 1: You've entered wrong input
Enter number 1: You've entered wrong input
Enter number 1: You've entered wrong input
Enter number 1: You've entered wrong input
推荐答案
您需要重新设置错误
p>
You need to reset the error
variable inside the loop
do {
error = 0;
//...
} while(error == 1);
这篇关于尝试抓住一个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!