Volume Calculator

Aim:

This webpage allows the user to choose a shape (cube, cylinder, or rectangular prism) and calculate its volume.

Algorithm:

The algorithm is as follows:

  1. Prompt the user to choose a shape.
  2. Depending on the choice, prompt the user to enter the required dimensions.
  3. Calculate the volume based on the chosen shape.
  4. Display the calculated volume.

Java Code:

import java.util.Scanner;

public class Volume {
    // Method to calculate volume of a cube
    public static double calculateVolume(double side) {
        return Math.pow(side, 3);
    }
    
    // Method to calculate volume of a cylinder
    public static double calculateVolume(double radius, double height) {
        return Math.PI * Math.pow(radius, 2) * height;
    }
    
    // Method to calculate volume of a rectangular prism
    public static double calculateVolume(double length, double width, double height) {
        return length * width * height;
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Choose a shape to calculate volume:");
        System.out.println("1. Cube");
        System.out.println("2. Cylinder");
        System.out.println("3. Rectangular Prism");
        System.out.print("Enter your choice (1, 2, or 3): ");
        int choice = scanner.nextInt();
        double volume = 0.0;
        
        switch (choice) {
            case 1:
                System.out.print("Enter the side length of the cube: ");
                double side = scanner.nextDouble();
                volume = calculateVolume(side);
                break;
            case 2:
                System.out.print("Enter the radius of the cylinder: ");
                double radius = scanner.nextDouble();
                System.out.print("Enter the height of the cylinder: ");
                double cylinderHeight = scanner.nextDouble();
                volume = calculateVolume(radius, cylinderHeight);
                break;
            case 3:
                System.out.print("Enter the length of the rectangular prism: ");
                double length = scanner.nextDouble();
                System.out.print("Enter the width of the rectangular prism: ");
                double width = scanner.nextDouble();
                System.out.print("Enter the height of the rectangular prism: ");
                double prismHeight = scanner.nextDouble();
                volume = calculateVolume(length, width, prismHeight);
                break;
            default:
                System.out.println("Invalid choice.");
                return;
        }

        System.out.println("Volume: " + volume);
    }
}
            

Output: