public void runMenu() {
int x = 1;
Scanner Option = new Scanner(System.in);
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:
break;
}
} catch (Exception e) {
System.out.println("Cant do that");
}
} while (Choice < 4);
System.out.println("Bye");
}
异常处理不起作用,例如如果我输入超出范围(例如 5),它应该显示类似“不能这样做”的内容。我应该输入一个 if 语句来定义条件 if 那么我该怎么做呢?现在,如果我输入错误的 key ,它只会打印“再见”。
最佳答案
您的问题是由于您的循环 while Choice < 4
.
您应该将循环更改为 while(true);
然后在 switch case 内创建一个 case 4,使用 System.exit(0)
退出程序
然后包含一个默认值,该默认值将通知用户他们输入了无效值
public void runMenu() {
int x = 1;
Scanner Option = new Scanner (System.in);
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:
break;
case 4:
System.out.println("Bye");
System.exit(0);
default:
System.out.println("Invalid Entry");
break;
}
}
catch (Exception e){
System.out.println("Cant do that");
}
} while (true);
}
关于java - 如何让错误显示出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35591007/