[英]How to return to main menu in switch case after executing a method?
How do I get get the menu to display again after the selected method executes?如何在所选方法执行后再次显示菜单?
I have the menu option print to the console.我有菜单选项打印到控制台。 Then it takes user input (1 - 6), calls according method, and then should return to the menu for the user to select from the menu again.
然后它接受用户输入(1 - 6),调用相应的方法,然后应该返回菜单供用户再次从菜单中选择。
After the selected method executes, the program just ends.选择的方法执行后,程序就结束了。
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;
}
}
}
Use a do while使用一段时间
do
{
System.out.println(mainMenu);
menuChoice = kbd.nextInt();
... switch/case ...
... remove the return statements from your cases.
} while (menuChoice != 6);
You also have to remove the return
from your case
s.您还必须从
case
删除return
。 Otherwise it will return out of main.否则它会从 main 中返回。 Replace them with
break
;用
break
替换它们;
This is how switch cases need to be这就是 switch case 需要的方式
switch (menuChoice)
{
case 1:
Do what you want.
break;
case 2:
...
break;
default:
...
break;
}
You don't usually need {
or if
inside the switch case.您通常不需要
{
或if
在开关盒内。
wrap your code inside将您的代码包装在里面
while(menuChoice != 6)
{
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.