To create a main menu loop in Java that continues to display the menu after a case has been executed, you can use a while
loop or a do-while
loop.
Here is an example of how you can use a while
loop to create a main menu loop:
Scanner sc = new Scanner(System.in); int choice; while (true) { // Display the menu System.out.println("1. Option 1"); System.out.println("2. Option 2"); System.out.println("3. Option 3"); System.out.println("4. Exit"); System.out.print("Enter your choice: "); choice = sc.nextInt(); switch (choice) { case 1: // code for option 1 break; case 2: // code for option 2 break; case 3: // code for option 3 break; case 4: System.exit(0); default: System.out.println("Invalid choice."); break; } }
In this example, the while
loop will continue to execute indefinitely until the user chooses to exit the program by selecting option 4
. The switch
statement is used to execute the appropriate code for each menu option.
Here is an example of how you can use a do-while
loop to achieve the same result:
Scanner sc = new Scanner(System.in); int choice; do { // Display the menu System.out.println("1. Option 1"); System.out.println("2. Option 2"); System.out.println("3. Option 3"); System.out.println("4. Exit"); System.out.print("Enter your choice: "); choice = sc.nextInt(); switch (choice) { case 1: // code for option 1 break; case 2: // code for option 2 break; case 3: // code for option 3 break; case 4: break; default: System.out.println("Invalid choice."); break; } } while (choice != 4);
In this example, the do-while
loop will continue to execute until the user chooses to exit the program by selecting option 4
. The switch
statement is used to execute the appropriate code for each menu option, as in the previous example.
Keep in mind that you can use any other looping construct, such as a for
loop, to create a main menu loop in Java. You can also add additional menu options and modify the code in the switch
statement to suit your needs.