In this tutorial, we will learn how to write a menu-driven program in Java. We can create a menu-driven program in Java using a switch statement and a looping statement such as do-while.
The switch statement executes the selected operation, while the loop repeatedly displays the menu until the user chooses to exit. Before going to write a menu-driven program, let’s first understand what a menu-driven program is.
What Is a Menu Driven Program in Java?
A menu-driven program in Java is a program that presents a menu containing a formatted list of options to the user. The user selects an option by entering its corresponding number or character, and the program executes the specific operation based on that choice.
The menu-driven program allows users to perform multiple operations within a single program without writing separate programs for each task.
For example, a simple calculator program may display the following menu like this:
===== Calculator Menu ===== 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Exit Enter your choice:
If the user enters 1, the program performs addition. If the user enters 2, it performs subtraction. Similarly, other options perform their respective operations. If they enter 5, the loop terminates and the program exits.
Core Java Concepts Used in Menu-Driven Programs
A menu-driven program generally uses the following Java programming concepts:
- Scanner class: Accepts user input from the console.
- Do-while loop: Keeps the program running and redisplays the menu until the user explicitly chooses to exit.
- Switch statement (or if-else): Directs program flow by selecting and executing the chosen operation.
- Break statement: Terminates each switch case to prevent fall-through behavior.
- Conditional statements (if-else): Handle edge cases and validation (such as preventing division by zero or catching invalid menu numbers).
How to Create a Menu Driven Program in Java?
To create a menu-driven program in Java, follow these steps:
- Import the Scanner class from the java.util package to accept input from the user’s keyboard.
- Create a Scanner object to read the user’s choice and other input values.
- Display a menu containing different options.
- Accept the user’s choice using the nextInt() method.
- Use a switch statement to execute the selected operation.
- Use a do-while loop to display the menu repeatedly.
- Terminate the program when the user selects the exit option.
- Close the Scanner object after completing the operations.
Let’s understand these steps with a practical Java program.
Menu Driven Program in Java Using Switch and Do-While Loop
Let’s write a Java program to create a menu-driven calculator program that performs four basic arithmetic operations:
- Addition
- Subtraction
- Multiplication
- Division
The program will continue displaying the menu until the user selects the Exit option.
Complete Java Program
// Import the Scanner class to handle user keyboard input
import java.util.Scanner;
public class MenuDrivenCalculator {
public static void main(String[] args) {
// Create a Scanner object to read inputs from the console
Scanner sc = new Scanner(System.in);
int choice; // Variable to store the user's menu selection
double num1, num2; // Variables to hold operands for calculations
// Use a do-while loop to guarantee the menu appears at least once
// and keeps looping until the user explicitly chooses to exit (choice 5)
do {
// Display the menu options
System.out.println("\n===== Calculator Menu =====");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Exit");
// Prompt and read the user's menu choice
System.out.print("Enter your choice: ");
choice = sc.nextInt();
// Use a switch statement to route execution based on the user's choice
switch (choice) {
case 1: // Handle Addition
System.out.print("Enter two numbers: ");
num1 = sc.nextDouble();
num2 = sc.nextDouble();
System.out.println("Result: " + (num1 + num2));
break; // Prevents fall-through to the next case
case 2: // Handle Subtraction
System.out.print("Enter two numbers: ");
num1 = sc.nextDouble();
num2 = sc.nextDouble();
System.out.println("Result: " + (num1 - num2));
break;
case 3: // Handle Multiplication
System.out.print("Enter two numbers: ");
num1 = sc.nextDouble();
num2 = sc.nextDouble();
System.out.println("Result: " + (num1 * num2));
break;
case 4: // Handle Division
System.out.print("Enter two numbers: ");
num1 = sc.nextDouble();
num2 = sc.nextDouble();
// Conditional check to prevent division by zero runtime issues
if (num2 != 0) {
System.out.println("Result: " + (num1 / num2));
} else {
System.out.println("Error! Division by zero is not allowed.");
}
break;
case 5: // Handle Program Exit
System.out.println("Exiting the program. Thank you!");
break;
default: // Catch-all for any invalid numbers (e.g., 6, -1, 99)
System.out.println("Invalid choice! Please enter a number between 1 and 5.");
}
} while (choice != 5); // The loop repeats as long as the user doesn't pick 5
// Close the scanner to free up system resources
sc.close();
}
}Output:
When we execute the above Java program, it displays the following menu:
===== Calculator Menu ===== 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Exit Enter your choice: 1 Enter two numbers: 25 15 Result: 40.0 ===== Calculator Menu ===== 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Exit Enter your choice: 3 Enter two numbers: 10 5 Result: 50.0 ===== Calculator Menu ===== 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Exit Enter your choice: 4 Enter two numbers: 20 0 Error! Division by zero is not allowed. ===== Calculator Menu ===== 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Exit Enter your choice: 5 Exiting the program. Thank you!
Explanation of the Java Program
Let’s understand how this menu-driven calculator program in Java works step by step.
- Import the Scanner class: First, we import the Scanner class from the java.util package to accept input from the keyboard.
- Create a Scanner object: We create a Scanner object named sc to read the user’s choice and numeric values.
- Declare variables: We declare an integer variable named choice to store the selected menu option and two double variables, num1 and num2, to store the numbers entered by the user.
- Display the menu: Inside the do-while loop, we display five options using System.out.println(). These options represent addition, subtraction, multiplication, division, and exit.
- Accept the user’s choice: The nextInt() method reads the option entered by the user and stores it in the choice variable.
- Use the switch statement: The switch statement checks the value of choice and executes the corresponding case block.
- Perform addition: When the user enters 1, the program accepts two numbers and adds them using the
+operator. - Perform subtraction: When the user enters 2, the program subtracts the second number from the first using the
-operator. - Perform multiplication: When the user enters 3, the program multiplies the two numbers using the
*operator. - Perform division: When the user enters 4, the program divides the first number by the second using the
/operator. Before performing division, it checks whether the second number is zero to avoid division by zero. - Exit the program: When the user enters option 5, the program displays an exit message. The loop terminates because the condition
choice != 5becomes false. - Handle invalid choices: The default block executes if the user enters an option other than 1, 2, 3, 4, or 5.
- Close the Scanner object: Finally, we close the Scanner object using the close() method.
How Does the Do-While Loop Work in a Menu Driven Program in Java?
The do-while loop is very useful for menu-driven programs because it executes the statements inside the loop at least once before checking the condition. This ensures the user always sees the menu and gets prompted for input upon starting the program.
Its general syntax is:
do {
// Statements to execute
} while (condition);In our calculator program, we used:
} while (choice != 5);This condition checks whether the user’s choice is anything other than 5 (the exit option):
- If the user enters 1, 2, 3, or 4, the condition evaluates to true, and the menu appears again.
- If the user enters 5, the condition evaluates to false, the loop terminates, and the program exits gracefully.
Therefore, the menu continues appearing until the user explicitly selects the Exit option.
Why Is the Switch Statement Used in a Menu-Driven Program?
The switch statement is used to execute different blocks of code based on the value of a variable or expression. In a menu-driven program, each menu option represents a distinct case:
- The program evaluates the value stored in the choice variable.
- It directly jumps to and executes the matching case block.
The Importance of the Break Statement:
Each case typically ends with a break statement. The break statement terminates the current switch block and transfers control outside of it.
The break statement terminates the current switch case and transfers control to the statement following the switch block. Without break statement, execution may continue into subsequent cases through switch fall-through.
Menu Driven Program in Java Using Modern Switch
Let’s write a Java program to build menu-driven calculator using a modern switch statement and do-while loop.
Complete Java Program
import java.util.Scanner;
public class ModernMenuDrivenCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int choice;
do {
// Display the menu options
System.out.println("\n===== Calculator Menu =====");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Exit");
// Accept user's choice
System.out.print("Enter your choice: ");
choice = sc.nextInt();
// Modern switch statement using arrow syntax (->)
// Notice: No 'break' statements are required!
switch (choice) {
case 1 -> {
System.out.print("Enter two numbers: ");
double num1 = sc.nextDouble();
double num2 = sc.nextDouble();
System.out.println("Result: " + (num1 + num2));
}
case 2 -> {
System.out.print("Enter two numbers: ");
double num1 = sc.nextDouble();
double num2 = sc.nextDouble();
System.out.println("Result: " + (num1 - num2));
}
case 3 -> {
System.out.print("Enter two numbers: ");
double num1 = sc.nextDouble();
double num2 = sc.nextDouble();
System.out.println("Result: " + (num1 * num2));
}
case 4 -> {
System.out.print("Enter two numbers: ");
double num1 = sc.nextDouble();
double num2 = sc.nextDouble();
if (num2 != 0) {
System.out.println("Result: " + (num1 / num2));
} else {
System.out.println("Error! Division by zero is not allowed.");
}
}
case 5 -> System.out.println("Exiting the program. Thank you!");
default -> System.out.println("Invalid choice! Please enter a number between 1 and 5.");
}
} while (choice != 5); // Repeat until user selects 5
sc.close(); // Clean up resource
}
}Output:
===== Calculator Menu ===== 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Exit Enter your choice: 1 Enter two numbers: 15.5 4.5 Result: 20.0 ===== Calculator Menu ===== 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Exit Enter your choice: 4 Enter two numbers: 10 0 Error! Division by zero is not allowed. ===== Calculator Menu ===== 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Exit Enter your choice: 5 Exiting the program. Thank you!





