Java for students logo
Explore the English language on a new scale using AI-powered English language navigator.

Switch-operated text menu

Abstract

Code snippet, demonstrating text menu operated by switch statement. There are stubs instead of actual menu handlers.

Source code

SwitchOperatedTextMenu.java

import java.util.Scanner;

 

public class SwitchOperatedTextMenu {

      public static void main(String[] args) {

            Scanner in = new Scanner(System.in);

            // print menu

            for (int i = 1; i <= 5; i++)

                  System.out.println(i + ". Menu item #" + i);

            System.out.println("0. Quit");

            // handle user commands

            boolean quit = false;

            int menuItem;

            do {

                  System.out.print("Choose menu item: ");

                  menuItem = in.nextInt();

                  switch (menuItem) {

                  case 1:

                        System.out.println("You've chosen item #1");

                        // do something...

                        break;

                  case 2:

                        System.out.println("You've chosen item #2");

                        // do something...

                        break;

                  case 3:

                        System.out.println("You've chosen item #3");

                        // do something...

                        break;

                  case 4:

                        System.out.println("You've chosen item #4");

                        // do something...

                        break;

                  case 5:

                        System.out.println("You've chosen item #5");

                        // do something...

                        break;

                  case 0:

                        quit = true;

                        break;

                  default:

                        System.out.println("Invalid choice.");

                  }

            } while (!quit);

            System.out.println("Bye-bye!");

      }

}

Download SwitchOperatedTextMenu.java

Sample run

1. Menu item #1

2. Menu item #2

3. Menu item #3

4. Menu item #4

5. Menu item #5

0. Quit

Choose menu item: 1

You've chosen item #1

Choose menu item: 5

You've chosen item #5

Choose menu item: 12

Invalid choice.

Choose menu item: 0

Bye-bye!

 

Partners Ads