how to build a java main menu

how to build a java main menu

To build a main menu in Java, you can use a loop to display a list of options to the user and allow them to select one. Here's an example of how you might do this:

import java.util.Scanner;

public class MainMenu {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        while (true) {
            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: ");

            int choice = scanner.nextInt();
            if (choice == 4) {
                break;
            }

            switch (choice) {
                case 1:
                    // Do something for option 1
                    break;
                case 2:
                    // Do something for option 2
                    break;
                case 3:
                    // Do something for option 3
                    break;
                default:
                    System.out.println("Invalid choice");
                    break;
            }
        }
    }
}
So‮ww:ecru‬w.lautturi.com

This code will display a main menu with four options to the user and allow them to select one. The loop will continue until the user selects option 4 (Exit). You can add additional options or modify the existing options as needed.

Created Time:2017-11-01 12:05:12  Author:lautturi