【发布时间】:2016-03-19 16:37:03
【问题描述】:
大家好,所以我的程序并没有真正捕捉到任何错误,即当我输入一个字母而不是一个有效数字时,它确实捕捉到了错误,但它不会返回到菜单,它只是显示语句。当我在 switch 语句之外使用数字时,即 5 它只是循环回到菜单而不显示错误。我的代码如下:
public void runMenu() {
Scanner Option = new Scanner (System.in);
int x = 1;
int Choice = 0;
do{
try{
System.out.println("Choose Option");
System.out.println("");
System.out.println("1: Create Account");
System.out.println("2: Check Account");
System.out.println("3: Take Action");
System.out.println("4: Exit");
System.out.println("Please choose");
Choice= Option.nextInt();
switch (Choice) //used switch statement instead of If else because more effective
{
case 1:
CreateAccount();
break; //breaks iteration
case 2:
selectAccount();
break;
case 3:
Menu();
int choice = UserInput();
performAction(choice);
break;
case 4:
System.out.println("Thanks for using the application");
System.exit(0);
default:
throw new Exception();
// x=2; //if code doesn't run successfully then x !=2 leading to exception
}
}
【问题讨论】:
-
如果出现异常,为什么要返回菜单?您在 catch 块中编写了
return语句 -
John - 请注意,您对问题的最后一次编辑使代码不可编译......一旦您修复了编译错误,行为就会有所不同。如果您希望人们帮助您,请不要这样做。
标签: java exception-handling switch-statement