C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Menu Driven Program - Overload Method - Java Programs

Write a menu-driven program using switch case to accept a choice from the user and according to the choice entered perform the following operations:

(a) To calculate and display the area of a circle using the formula:
Area = (π × radius2) where π = 22 / 7

(b) To calculate and display the area of a rectangle using the formula:
Area = (length × breadth)

(c) To calculate and display the area of a triangle using the formula:
Area = 1 / 2 × base × height

(d) To calculate and display the area of a square using the formula:
Area = side2

For an incorrect option, an appropriate error message should be displayed.

import java.util.Scanner; class Menu{ public static void main(String[] args){ Scanner in = new Scanner(System.in); System.out.println("1. Area of circle"); System.out.println("2. Area of rectangle"); System.out.println("3. Area of triangle"); System.out.println("4. Area of square"); System.out.print("Enter your choice: "); int choice = Integer.parseInt(in.nextLine()); switch(choice){ case 1: System.out.print("Radius = "); double r = Double.parseDouble(in.nextLine()); double a = 22.0 / 7 * r * r; System.out.println("Area = " + a); break; case 2: System.out.print("Length = "); double l = Double.parseDouble(in.nextLine()); System.out.print("Breadth = "); double b = Double.parseDouble(in.nextLine()); a = l * b; System.out.println("Area = " + a); break; case 3: System.out.print("Base = "); b = Double.parseDouble(in.nextLine()); System.out.print("Height = "); double h = Double.parseDouble(in.nextLine()); a = 1.0 / 2 * b * h; System.out.println("Area = " + a); break; case 4: System.out.print("Side = "); double s = Double.parseDouble(in.nextLine()); a = s * s; System.out.println("Area = " + a); break; default: System.out.println("Invalid choice!"); } } }

Output

 
 OUTPUT 1: 
1. Area of circle
2. Area of rectangle
3. Area of triangle
4. Area of square
Enter your choice: 1
Radius = 10
Area = 314.2857142857143

 OUTPUT 2: 
1. Area of circle
2. Area of rectangle
3. Area of triangle
4. Area of square
Enter your choice: 2
Length = 10
Breadth = 20
Area = 200.0