gpt4 book ai didi

java - 嵌套在 do-while 循环中的 try-catch 没有实际循环是否有原因?

转载 作者:行者123 更新时间:2023-12-02 10:06:18 26 4
gpt4 key购买 nike

我有一个简单的 switch-case 嵌套在 do while 循环中。在我的代码中,因此 switch case 的输入是通过用户进行的。所以我试图捕获一个InputMismatchException,然后循环继续{再次循环},但它停止了一切。如何让它继续循环?

   public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Equation Solver");
char ch;
do
{
try{
System.out.println("\nPlease choose\n");
System.out.println("1. Suvat Equations");
System.out.println("2. Energy Equations");
System.out.println("3. The Doppler Effect Calculations");
System.out.println("4. Gravitational Force Equation");
System.out.println("5. Support");
System.out.println("6. Graph");

int choice = scan.nextInt();

switch (choice)
{
case 1 :
System.out.println("\nPlease choose according to the variable you want to find\n");
System.out.println("1. Initial Velocity");
System.out.println("2. Final Velocity");
System.out.println("3. Acceleration");
System.out.println("4. Distance Travelled");
System.out.println("5. Time Taken");
System.out.println("6. Otherwise Cancel");

try{
int choiceCase1 = scan.nextInt();

switch(choiceCase1){
case 1 :
System.out.println("Please ");
Equation1();
break;
case 2 :
Equation1();
break;
case 3 :
Equation1();
break;
case 4 :
Equation1();
break;
case 5 :
Equation1();
break;
case 6 :
break;
default :
System.out.println("Wrong Entry \n ");
break;
}



}catch (InputMismatchException e){
System.out.println("please stop");
}

case 2 :
Equation1();
break;
case 3 :
System.out.println("Enter integer element to insert");

break;
case 4 :
System.out.println("Enter integer element to insert");

break;
case 5 :

break;
case 6 :

break;
default :
System.out.println("Wrong Entry \n ");
break;
}
} catch (InputMismatchException s){
System.out.println("Caught Exception")
} finally{

System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);
}
} while (ch == 'Y'|| ch == 'y');

}

我希望用户能够输入 y 然后重复循环,但不允许这样做

最佳答案

来自:https://www.tutorialspoint.com/java/java_break_statement.htm

When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.

您的中断声明位于:

    } catch (InputMismatchException s){
break;
}

正在结束循环。

编辑:此 try/catch 语句位于 switch 语句之外。所以break不是退出switch语句,而是退出循环。

关于java - 嵌套在 do-while 循环中的 try-catch 没有实际循环是否有原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55315310/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com