【发布时间】:2021-11-20 03:45:15
【问题描述】:
我正在尝试在 do-while 循环中使用 try-catch 语句。逻辑似乎有效,但 do 循环不会一遍又一遍地循环。如果它进入 catch 中,它似乎只是跳出了 do 循环。
private boolean madeChoice = false;
public void whatToDo(){
System.out.println("");
System.out.println("");
System.out.println("=====================================");
System.out.println("Welcome");
System.out.println("=====================================\n");
System.out.println("What would you like to do today? Your choices are: \n");
choices();
do{
try{
System.out.println("");
System.out.println("Please enter your choice");
int numberEntered = keyboard.nextInt();
if(numberEntered > 3 || numberEntered < 1){
System.out.println("-----------------------------------------------------------");
System.out.println("That is not a choice. Please choose from the following: \n");
choices();
numberEntered = keyboard.nextInt();
}else{
System.out.println("That is a good CHOICE");
madeChoice = true;
}
}catch (InputMismatchException e){
System.out.println("-----------------------------------------------------------");
System.out.println("This is not a number. Please choose from the following: \n");
choices();
}
}while(!madeChoice);
}
private void choices(){
System.out.println("1. Add a new set into your account");
System.out.println("2. See all the sets in your account");
System.out.println("3. Exit the Account Manger.");
}
【问题讨论】:
-
似乎在将 madeChoice 设置为 true 之前出现错误,因此 madeChoice 保持为 false 并且循环在那里停止。也许你应该改变你处理问题的方式。真的需要 madeChoice 变量吗?您希望循环何时准确结束?编辑:您可以在 catch 子句中将 madeChoice 设置为 true 吗?
-
所以我在 whatToDo 方法上方将 madeChoice 设置为 false。抱歉,我应该添加那个。
-
你不想在
!madeChoice循环吗? -
我希望循环仅在用户输入 1,2 或 3 时结束。如果有其他任何情况,如果它应该被 if-else 语句捕获,或者如果它是 catch 方法中的错误。
-
当用户输入错误的数字时,
madeChoice有什么值?该值会使循环退出还是继续?