Write a program to Menu driven program using switch statement


This Java program is a menu-driven calculator that allows the user to perform basic arithmetic operations on two numbers. The program displays a menu of options (addition, subtraction, multiplication, and division) and prompts the user to select an option. Based on the user's choice, the program asks the user to enter two numbers and performs the selected operation. Here's how the program works:

  • The program displays a menu of options using System.out.println().
  • The user selects an option by entering a number between 1 and 4 using Scanner.nextInt() method, which is stored in the variable ch.
  • The program uses a switch statement to perform the corresponding operation based on the user's choice.
  • If the user selects an invalid option (not between 1 and 4), the program prints an error message.

Source Code

import java.util.Scanner;
public class Menu_Driven
{
    public static void main(String args[])
    {
        Scanner input = new Scanner(System.in);
        int a,b,ch;
 
        System.out.println("1. Addition");
        System.out.println("2. Subtraction");
        System.out.println("3. Multiplication");
        System.out.println("4. Division");
        System.out.print("Select your Choice(1-4) : ");
        ch = input.nextInt();
 
        switch(ch)
        {
            case 1:
                System.out.print("Enter the Number 1 :");
                a=input.nextInt();
                System.out.print("Enter the Number 2 :");
                b=input.nextInt();
                System.out.print("Addition = " + (a+b));
                break;
            case 2:
                System.out.print("Enter the Number 1 :");
                a=input.nextInt();
                System.out.print("Enter the Number 2 :");
                b=input.nextInt();
                System.out.print("Subtraction = " + (a-b));
                break;
            case 3:
                System.out.print("Enter the Number 1 :");
                a=input.nextInt();
                System.out.print("Enter the Number 2 :");
                b=input.nextInt();
                System.out.print("Multiplication = " + (a*b));
                break;
            case 4:
                System.out.print("Enter the Number 1 :");
                a=input.nextInt();
                System.out.print("Enter the Number 2 :");
                b=input.nextInt();
                System.out.print("Division = " + (a/b));
                break;
            default:
                System.out.print("Invalid Choice...Please Try Again !!!");
        }
    }
}
 

Output

1. Addition
2. Subtraction
3. Multiplication
4. Division
Select your Choice(1-4) : 2
Enter the Number 1 :45
Enter the Number 2 :12
Subtraction = 33