Saturday, 4 November 2023

Write a Java program to calculate area of Circle, Triangle & Rectangle.(Use Method Overloading) -Core java slip18

 

Write a Java program to calculate area of Circle, Triangle & Rectangle.(Use Method Overloading)    

import java.util.Scanner;

import java.io.*;

public class AreaCalculator {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

 

        System.out.println("1. Calculate the area of a circle");

        System.out.println("2. Calculate the area of a triangle");

        System.out.println("3. Calculate the area of a rectangle");

        System.out.print("Enter your choice (1/2/3): ");

        int choice = scanner.nextInt();

 

        switch (choice) {

            case 1:

                System.out.print("Enter the radius of the circle: ");

                double radius = scanner.nextDouble();

                System.out.println("Area of the circle: " + calculateArea(radius));

                break;

 

            case 2:

                System.out.print("Enter the base of the triangle: ");

                double base = scanner.nextDouble();

                System.out.print("Enter the height of the triangle: ");

                double height = scanner.nextDouble();

                System.out.println("Area of the triangle: " + calculateArea(base, height));

                break;

 

            case 3:

                System.out.print("Enter the length of the rectangle: ");

                double length = scanner.nextDouble();

                System.out.print("Enter the width of the rectangle: ");

                double width = scanner.nextDouble();

                System.out.println("Area of the rectangle: " + calculateArea(length, width));

                break;

 

            default:

                System.out.println("Invalid choice");

        }

    }

 

    public static double calculateArea(double radius) {

        return Math.PI * radius * radius;

    }

 

    public static double calculateArea(double base, double height) {

        return 0.5 * base * height;

    }

 

    public static double calculateArea(double length, double width) {

        return length * width;

    }

}