Reputation: 55
I've created a menu in Java wherein each option has another menu. 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. Choosing option 4 (exit submenu) refreshes to the submenu rather than the main menu. I think what's causing this is the while loop I have for the submenu. 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.
Upvotes: 1
Views: 3193
Reputation: 201517
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.
That is move the main menu display and choice
input to something like
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){
Upvotes: 4