Menu Example using Java while Loop

Here is an example of using a while loop in Java to create a simple menu that allows the user to select different options:

package whileL_loop;

import java.util.Scanner;

/**
 * An example of using a while loop in Java to create a simple menu that allows
 * the user to select different options
 * 
 * @author Mamun Kayum
 *
 */
public class WhileLoopMenuExample {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int choice = 0;

		while (choice != 4) {
			System.out.println("Main 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 = input.nextInt();

			switch (choice) {
			case 1:
				System.out.println("You chose Option 1.");
				break;
			case 2:
				System.out.println("You chose Option 2.");
				break;
			case 3:
				System.out.println("You chose Option 3.");
				break;
			case 4:
				System.out.println("Goodbye!");
				break;
			default:
				System.out.println("Invalid choice. Please try again.");
				break;
			}
			System.out.println();
		}
	}
}

In this example, a while loop is used to repeatedly display a menu of options until the user chooses to exit the program. The loop condition choice != 4 is checked at the beginning of each iteration to determine if the loop should continue or exit.

Inside the loop, the menu options are displayed using System.out.println() statements. The user’s input is then read using the Scanner class, and the user’s choice is stored in the choice variable. A switch statement is used to perform different actions based on the user’s choice. If the user chooses option 4, the loop will exit and the program will end. Otherwise, the loop will continue and display the menu again.

Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.

Follow us on social media
Follow Author