[英]How to return to main menu in switch case after executing a method?
如何在所选方法执行后再次显示菜单?
我有菜单选项打印到控制台。 然后它接受用户输入(1 - 6),调用相应的方法,然后应该返回菜单供用户再次从菜单中选择。
选择的方法执行后,程序就结束了。
public static void main (String[] arg) {
Scanner kbd = new Scanner(System.in);
String mainMenu = ("Select a choice from the menu: \n"
+ "1. Add new DVD entry\n"
+ "2. Look Up DVD Entry\n"
+ "3. Display DVDs By Category\n"
+ "4. Remove DVD Entry\n"
+ "5. Save Data\n"
+ "6. Exit");
System.out.println(mainMenu);
menuChoice = kbd.nextInt();
while (menuChoice < 1 || menuChoice > 6) {
System.out.print("\nError! Incorrect choice.\n");
System.out.println(mainMenu);
menuChoice = kbd.nextInt();
}
switch (menuChoice) {
case 1: {
// method code
}
else {
// method code
return;
}
}
case 2: {
// method code
return;
}
case 3: {
// method code
return;
}
case 4: {
// method code
return;
}
case 5: {
// method code
return;
}
case 6: {
// method code
System.exit(0);
return;
}
}
}
使用一段时间
do
{
System.out.println(mainMenu);
menuChoice = kbd.nextInt();
... switch/case ...
... remove the return statements from your cases.
} while (menuChoice != 6);
您还必须从case
删除return
。 否则它会从 main 中返回。 用break
替换它们;
这就是 switch case 需要的方式
switch (menuChoice)
{
case 1:
Do what you want.
break;
case 2:
...
break;
default:
...
break;
}
您通常不需要{
或if
在开关盒内。
将您的代码包装在里面
while(menuChoice != 6)
{
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.