askIT

Java Menu (If, else if and else)

Lagre Download example files

We can use if, else if and else to create a menu. We do this by printing a menu, also ask the user what he wants to do. The procedure in detail is as follows:

package menu;

import java.util.Scanner;

public class Menu {

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

                // Print menu
                System.out.println("--- MENU --- ");
                System.out.println("[1] New game");
                System.out.println("[2] Load saved game");
                System.out.println("[3] Settings");
                System.out.println("[-1] End game");
                System.out.println("");
                       
                // Ask for menu
                System.out.print("Menu choice: ");
                int menu = scanner.nextInt();
               
                // Go trough menu possibilities
                if(menu == 1){
                        System.out.println("--- NEW GAME ---");               
                }
                else if(menu == 2){
                        System.out.println("--- LOAD SAVED GAME ---");
                }
                else if(menu == 3){
                        System.out.println("--- SETTINGS ---");
                }
                else{
                        System.out.println("--- END GAME ---");
                }
        }// main
       
       
} // menu

When the code is executed the output will this if you choose menu option 2:
01_meny

Assignments

1. Program a menu to a booking system. The menu shall have new booking, view bookings, search for bookings and quit program.

2. Create a program that you can select menu items Running, Biking and Hunting. If you choose one of these three should bring up a new submenu. The submenu shall be:

Run
  Sneakers
  Running clothing
  Watches
  Water Bottle

Bicycle:
  Mountain bike
  Hybrid Bicycle
  Electrical bicycle
  Scooter

Hunting:
  Hunting Equipment
  Hunting Clothes
  Hunting Boots

3. Instead of a menu where you should enter numbers this program shall have the day name as input (Monday, Tuesday, Wednesday, etc ..).
Can you get it to be indifferent if one writes day name with uppercase or lowercase (Monday and monday)?

Add comment

avatar_blank_60.png

Comment:

Name:

Email:

Comments

No comments yet. You can be the first one to comment. Just write your comment in the form and click on the submit button.