Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Menu Driven Program in Java?
2.1.
Code Examples
2.2.
Calculator Example
2.3.
Bank Transaction Example
3.
Uses of Menu-Driven Programs
4.
Frequently Asked Questions
4.1.
How do you create a menu-driven program in Java?
4.2.
How to handle errors in menu-driven programs in Java?
4.3.
What are some of the uses of menu-driven programming?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Menu Driven Program in Java

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

As the name suggests, menu-driven programming refers to writing programs where the program first interacts with the user, and henceforth, the user is offered a fixed number of choices to control the flow of the program. 

A menu-driven program takes user input by presenting a list of options, known as the menu, from which the user can select one. These choices are offered to the user, and based on the selection the user makes, the program has different statements that get executed. 

Typical systems that process Menu Driven programs include washing machines with microprocessors and automated teller machines (ATMs). 

Menu-driven programs in Java refer to the programs where the program will run on set cases using a switch or, if else, based on the input provided by the user.

Menu-driven programs in Java


In Java Menu driven programs allow the user to interact with the program using a Menu and various Sub menus. These programs are designed to make the user experience more intuitive and user-friendly by presenting the user with a set of options to choose from rather than requiring them to input specific commands or functions.

What is Menu Driven Program in Java?

These types of programs offer a list of input choices to the user in the form of a menu, and then, based on the input, the program gets executed.

Code Examples

Below are some examples of menu-driven programs in Java: 

Calculator Example

In the below example, we provide five choices of operations, addition, subtraction, multiplication, division, and exit the program.

Here the user is confined to these choices, and this is displayed to him as a menu where the choice then executes the program accordingly using the switch statements where we define the code blocks for each of the cases.

Calculator Example

Code in Java 

import java.util.Scanner;
public class Calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int choice;
        double num1, num2, result;
        
        // display menu and get user's choice
        do {
            System.out.println("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");
            System.out.print("Enter your choice: ");
            choice = scanner.nextInt();
            
            //Execute the selected operation
            switch (choice) {
                case 1:
                    // addition
                    System.out.print("Enter first number: ");
                    num1 = scanner.nextDouble();
                    System.out.print("Enter second number: ");
                    num2 = scanner.nextDouble();
                    result = num1 + num2;
                    System.out.println("Result: " + result);
                    break;
                case 2:
                    // subtraction
                    System.out.print("Enter first number: ");
                    num1 = scanner.nextDouble();
                    System.out.print("Enter second number: ");
                    num2 = scanner.nextDouble();
                    result = num1 - num2;
                    System.out.println("Result: " + result);
                    break;
                case 3:
                    // multiplication
                    System.out.print("Enter first number: ");
                    num1 = scanner.nextDouble();
                    System.out.print("Enter second number: ");
                    num2 = scanner.nextDouble();
                    result = num1 * num2;
                    System.out.println("Result: " + result);
                    break;
                case 4:
                    // division
                    System.out.print("Enter first number: ");
                    num1 = scanner.nextDouble();
                    System.out.print("Enter second number: ");
                    num2 = scanner.nextDouble();
                    if (num2 == 0) {
                        // divide-by-zero error
                        System.out.println("Cannot divide by zero");
                    } else {
                        result = num1 / num2;
                        System.out.println("Result: " + result);
                    }
                    break;
                case 5:
                    //Exit the program
                    System.out.println("Exiting program...");
                    break;
                default:
                    // invalid choice
                    System.out.println("Invalid choice, please try again.");
                    break;
            }
        } while (choice != 5); // repeat until the user chooses to exit
        
        scanner.close(); // close the scanner
    }
}

 

Output

Number Output

Bank Transaction Example

In the above example, we display a menu to the user and give him four choices. The choices are to Check the Balance, Withdrawal, deposit, and exit the program. 

  • Based on the choice of the user, we then write cases in our switch block. 
     
  • In check balance, we return the balance. 
     
  • In withdrawal, we reduce it by the user input; in deposit, we add the amount entered by the user, which we take as input into the old balance and display the new balance.
Bank Transaction

Code in Java

import java.util.Scanner;
public class BankTransaction {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int choice;
        double balance = 0;
        
        // display menu and get user's choice
        do {
            System.out.println("Menu:");
            System.out.println("1. Check Balance");
            System.out.println("2. Deposit");
            System.out.println("3. Withdraw");
            System.out.println("4. Exit");
            System.out.print("Enter your choice: ");
            choice = scanner.nextInt();
            
            //Execute the selected operation
            switch (choice) {
                case 1:
                    // check balance
                    System.out.println("Balance: " + balance);
                    break;
                case 2:
                    // deposit
                    System.out.print("Enter amount to deposit: ");
                    double deposit = scanner.nextDouble();
                    balance += deposit;
                    System.out.println("New Balance: " + balance);
                    break;
                case 3:
                    // withdraw
                    System.out.print("Enter amount to withdraw: ");
                    double withdraw = scanner.nextDouble();
                    if (withdraw > balance) {
                        //Insufficient balance
                        System.out.println("Insufficient balance");
                    } else {
                        balance -= withdraw;
                        System.out.println("New Balance: " + balance);
                    }
                    break;
                case 4:
                    //Exit the program
                    System.out.println("Exiting program...");
                    break;
                default:
                    // invalid choice
                    System.out.println("Invalid choice, please try again.");
                    break;
            }
        } while (choice != 4); // repeat until the user chooses to exit
        
        scanner.close(); // close the scanner
    }
}

 

Output

Banking Output
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Uses of Menu-Driven Programs

Here let's discuss some real-world applications of Menu Driven Programs.

  • Error reduction- Because the program executes only for some inputs that are provided to the user's GUI, the chance of getting an error is reduced considerably, as the input is already set.
  • Input ambiguity is also resolved in menu-driven programs because these programs limit the number of characters that can be given as input.
  • Many utilities, such as file compression programs, backup tools, and network diagnostics tools, are menu-driven. These programs allow users to perform specific functions, such as compressing files or performing a network trace.
     

Also check out Addition of Two Numbers in Java here.

Frequently Asked Questions

How do you create a menu-driven program in Java?

A menu-driven program in Java typically involves displaying a set of options to the user, getting the user's input, and executing the corresponding code based on the user's input. This can be done using a switch statement or if-else statements.

How to handle errors in menu-driven programs in Java?

The main reason for errors in menu-driven programs can be due to the user's input, and we can validate user input before executing the other code for that input.In menu-driven programs, errors can be handled by implementing mechanisms like input validation, range checking, and error messages. These mechanisms ensure that users input is valid and has appropriate values only.

What are some of the uses of menu-driven programming?

Some real-world applications of menu-driven programming involve banking applications, e-commerce sites, and database applications.

Conclusion

After going through this article, you should be able to analyze the need for menu-driven programs in Java because they simplify the code execution by reducing the different cases for the program to execute. They provide users with a clear set of options to choose from, making the program more user-friendly and less prone to errors. All in all, they also make the program more user-friendly and easy to execute on the GUI side also. 

Looking for more topics like this to read? Don't worry; Coding Ninjas has you covered. 

Refer:

Java Tokens

Java Verify

Java Hello World Program

Difference between While and Do While Loops

Access modifiers in java

for more articles like this.

Previous article
Prime Number Program in Java
Next article
Palindrome Program in Java
Live masterclass