退出嵌套的switch语句到外部switch语句

时间:2014-08-11 00:36:23

标签: java nested switch-statement

我已经用Java创建了一个菜单,其中每个选项都有另一个菜单。我想知道我是否可以退出内部菜单返回主菜单。

编辑:添加了主菜单选项

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);
    }
    }

这是我的主菜单。我只编写了第一个选项的代码和退出的选项。

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"); 
            }
    }
}

这是我将第二个switch语句放入其中的方法。选择选项4(退出子菜单)刷新到子菜单而不是主菜单。我认为造成这种情况的原因是我对子菜单的while循环。我不想取消此选项,因为我希望能够在完成案例1-3之后继续做出选择。

1 个答案:

答案 0 :(得分:4)

我相信你遇到的问题是

while(true){
  // HERE
  switch(choice){

您需要添加代码才能再次获取choice,否则它将始终是您最初输入的内容。

即将主菜单显示和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){
相关问题