You are developing a program that calculates the area of different shapes. Implement a Java program that contains a main method and the following methods:
calculateAreaOfCircle
that takes the radius of a circle as a parameter and returns the area of the circle.calculateAreaOfRectangle
that takes the length and width of a rectangle as parameters and returns the area of the rectangle.calculateAreaOfTriangle
that takes the base and height of a triangle as parameters and returns the area of the triangle.In the main method, prompt the user to enter the dimensions of a circle, a rectangle, and a triangle, and display their respective areas.
Use the following formulas to calculate the areas:
You may assume that the user will only provide valid dimensions (radius, length, width, base, and height).
Write the complete Java program to solve this problem.
Example Output:
Enter the radius of the circle: 4
Enter the length and width of the rectangle: 5 6
Enter the base and height of the triangle: 3 8
Area of the circle: 50.27
Area of the rectangle: 30
Area of the triangle: 12.0
Please write your solution code below:
Answer:
import java.util.Scanner;
public class AreaCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the radius of the circle: ");
double circleRadius = scanner.nextDouble();
System.out.print("Enter the length and width of the rectangle: ");
double rectangleLength = scanner.nextDouble();
double rectangleWidth = scanner.nextDouble();
System.out.print("Enter the base and height of the triangle: ");
double triangleBase = scanner.nextDouble();
double triangleHeight = scanner.nextDouble();
double circleArea = calculateAreaOfCircle(circleRadius);
double rectangleArea = calculateAreaOfRectangle(rectangleLength, rectangleWidth);
double triangleArea = calculateAreaOfTriangle(triangleBase, triangleHeight);
System.out.println("\nArea of the circle: " + circleArea);
System.out.println("Area of the rectangle: " + rectangleArea);
System.out.println("Area of the triangle: " + triangleArea);
}
public static double calculateAreaOfCircle(double radius) {
return Math.PI * Math.pow(radius, 2);
}
public static double calculateAreaOfRectangle(double length, double width) {
return length * width;
}
public static double calculateAreaOfTriangle(double base, double height) {
return (base * height) / 2;
}
}
Explanation:
Scanner
class is imported to allow user input.main
method, we prompt the user to enter the dimensions of the circle, rectangle, and triangle.calculateAreaOfCircle
, calculateAreaOfRectangle
, and calculateAreaOfTriangle
methods calculate the areas.