[英]Exiting out of nested switch statement to outer switch statement
I've created a menu in Java wherein each option has another menu. 我已经用Java创建了一个菜单,其中每个选项都有另一个菜单。 I want to know if I can exit from the inner menu back to the main menu.
我想知道是否可以从内部菜单返回主菜单。
Edit: Added Main Menu options 编辑:添加了主菜单选项
System.out.println("Main Menu");
System.out.println("1. Hourly Employees");
System.out.println("2. Salary Employees");
System.out.println("3. Commission Employees");
System.out.println("4. Weekly Calculations");
System.out.println("5. Exit Program");
while(true){
switch(choice){
case 1:
HourlyEmployeeChoice HEC = new HourlyEmployeeChoice();
//HourlyEmployeeChoice is a class with HEmployeeMenu() method
HEC.HEmployeeMenu();
break;
//case 2-4: to be added later
case 5:
System.out.println("Goodbye!");
System.exit(0);
}
}
This is my main menu. 这是我的主菜单。 I only wrote the code for the first option and the option to exit.
我只为第一个选项和退出选项编写了代码。
public void HEmployeeMenu(){
while(true){
//submenu options
int hourlyChoice = userChoice.nextInt();
switch(hourlyChoice) {
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
case 4: //exit submenu
return;
default:
System.out.println("Please make a valid selection");
}
}
}
This is the method I put my second switch statement inside. 这是我将第二个switch语句放入其中的方法。 Choosing option 4 (exit submenu) refreshes to the submenu rather than the main menu.
选择选项4(退出子菜单)将刷新到子菜单,而不是主菜单。 I think what's causing this is the while loop I have for the submenu.
我认为导致此问题的是子菜单的while循环。 I don't want to take this option off though, because I want to be able to continue making choices after doing cases 1-3.
但是,我不想取消此选项,因为我希望能够在进行案例1-3之后继续做出选择。
I believe the problem you are having is 我相信您遇到的问题是
while(true){
// HERE
switch(choice){
You need to add code to get the choice
again, otherwise it will always be whatever you first entered. 您需要添加代码以再次获得
choice
,否则它将始终是您首次输入的内容。
That is move the main menu display and choice
input to something like 那就是将主菜单显示和
choice
输入移到类似
while(true){
System.out.println("Main Menu"); // <-- Added based on your edit.
System.out.println("1. Hourly Employees");
System.out.println("2. Salary Employees");
System.out.println("3. Commission Employees");
System.out.println("4. Weekly Calculations");
System.out.println("5. Exit Program");
int choice = userChoice.nextInt(); // <-- HERE
switch(choice){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.