我把这个try / catch包裹在do / while循环中,因为在try / catch抛出错误消息之后,我希望它循环回到顶部。我尝试do / while,while,我尝试将while循环放在我的代码中的不同位置,但没有任何作用。程序运行正常,直到抛出异常,然后进入无限循环。之后显示错误消息,我只想让它循环回到顶部。
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
Integer userInput;
do {
try{
System.out.print("Enter a number? \n");
userInput = input.nextInt();
if ( userInput == 1 )
Animal1.displayMessage ();//Display the total
if( userInput == 2 )
Animal2.displayMessage ();//Display the total
}
catch (Exception e) {
System.out.println(" That's not right ");
break;
}
} while (true);
}
}
这是显示错误消息后的作用。
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
Enter a number?
如果我不停止它,它就会继续前进。
答案 0 :(得分:1)
您可以尝试以下解决方法:
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
Integer userInput;
do {
try{
System.out.print("Enter a number? \n");
userInput = input.nextInt();
if ( userInput == 1 )
Animal1.displayMessage ();//Display the total
if( userInput == 2 )
Animal2.displayMessage ();//Display the total
}
catch (Exception e) {
System.out.println(" That's not right ");
input.next();
}
} while (true);
}
}
或者如果你想避免试试:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Integer userInput = 0;
do {
System.out.print("Enter a number? \n");
if (input.hasNextInt())
userInput = input.nextInt();
else {
System.out.println(" That's not right ");
input.next();
}
if (userInput == 1)
Animal1.displayMessage ();//Display the total
;// Display the total
if (userInput == 2)
Animal2.displayMessage ();//Display the total
} while (true);
}
答案 1 :(得分:0)
您可以提供3个选项 - 退出一个选项
System.out.print("Enter a number? \n 1 to display Animal1 total\n2 to display Animal2 total\n 3 to exit");
在while循环中,您可以添加
if ( userInput == 3) break;
答案 2 :(得分:-1)
您需要将try / catch语句放在循环之外。