gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:18:15 30 4
gpt4 key购买 nike

我用 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 之后能够继续做出选择。

最佳答案

我相信你遇到的问题是

while(true){
// HERE
switch(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){

关于java - 退出嵌套的 switch 语句到外部 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25234374/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com