Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.lang.Math.*;
- import java.text.DecimalFormat;
- // Java program to calculate the volume of a sphere, cube or tetrahedron
- class VolumeOfShapes {
- private static DecimalFormat df2 = new DecimalFormat("#.##");
- public static void main(String [] args) {
- Shape();
- }
- public static void Shape(){
- Scanner in = new Scanner(System.in);
- System.out.println("What shape would you like me to calculate the volume of?");
- String shape;
- shape = in.nextLine();
- switch(shape)
- {
- case "sphere":
- System.out.println("What is the radius of the sphere?");
- double radius = in.nextDouble();
- Sphere(radius);
- break;
- case "cube":
- System.out.println("What is the radius of the cube?");
- double width = in.nextDouble();
- Cube(width);
- break;
- case "tetrahedron":
- System.out.println("What is the radius of the tetrahedron?");
- double edge = in.nextDouble();
- Tetrahedron(edge);
- break;
- case "quit":
- break;
- default:
- System.out.println("Please enter 'sphere', 'cube' or 'tetrahedron' to continue. Enter 'quit' to exit program.");
- Shape();
- }
- }
- private static double Sphere(double radius){
- double x = (4.0/3.0);
- double y = (radius * radius * radius);
- double volume = (x * Math.PI) * y;
- System.out.println("Math.pi = " + Math.PI + "4/3 or x = " + x + "r squared or y = " + y + "volume = " + volume);
- System.out.println("The volume of this sphere with radius " + radius + " is " + df2.format(volume));
- return volume;
- }
- private static double Cube(double width){
- double volume = (width * width * width);
- System.out.println("The volume of this cube of width " + width + " is " + df2.format(volume));
- return volume;
- }
- private static void Tetrahedron(double edge){
- double a = (edge * edge * edge);
- double x = 6 * (Math.sqrt(2));
- double volume = a / x;
- System.out.println("The volume of this tetrahedron with edge " + edge + " is " + df2.format(volume));
- return volume;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement