Skip to content

Instantly share code, notes, and snippets.

@jimmykurian
Created February 21, 2012 05:41
Show Gist options
  • Save jimmykurian/1874009 to your computer and use it in GitHub Desktop.
Save jimmykurian/1874009 to your computer and use it in GitHub Desktop.
An object oriented version of Geometry.java that will compute the volume and surface area of a sphere with radius r, a cylinder with circular base with radius r and height h, and a cone with circular base with radius r and height h. Written in Java.
//Cone.java - Jimmy Kurian
public class Cone
{
private double r;
private double h;
public Cone(double aRadius, double aHeight)
{
r = aRadius;
h = aHeight;
}
public double getVolume()
{
return (1.0 / 3.0) * Math.PI * r * r * h;
}
public double getSurfaceArea()
{
return Math.PI * r * (h + r);
}
}
//Cylinder.java - Jimmy Kurian
public class Cylinder
{
private double r;
private double h;
public Cylinder(double aRadius, double aHeight)
{
r = aRadius;
h = aHeight;
}
public double getVolume()
{
return h * Math.PI * r * r;
}
public double getSurfaceArea()
{
return (2.0 * r * Math.PI * h) + (2.0 * Math.PI * r * r);
}
}
//GeometryTester2.java - Jimmy Kurian
import java.util.Scanner;
public class GeometryTester2
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Please enter the radius: ");
double r = in.nextDouble();
System.out.println("Please enter the height: ");
double h = in.nextDouble();
Sphere sp = new Sphere(r);
double v = sp.getVolume();
double s = sp.getSurfaceArea();
System.out.println("The volume of the sphere is: " + v);
System.out.println("The surface area of the sphere is: " + s);
Cylinder cy = new Cylinder(r, h);
v = cy.getVolume();
s = cy.getSurfaceArea();
System.out.println("The volume of the cylinder is: " + v);
System.out.println("The surface area of the cylinder is: " + s);
Cone co = new Cone(r, h);
v = co.getVolume();
s = co.getSurfaceArea();
System.out.println("The volume of the cone is: " + v);
System.out.println("The surface area of the cone is: " + s);
}
}
//Sphere.java - Jimmy Kurian
public class Sphere
{
private double r;
public Sphere(double aRadius)
{
r = aRadius;
}
public double getVolume()
{
return (4.0 / 3.0) * Math.PI * r * r * r;
}
public double getSurfaceArea()
{
return 4.0 * Math.PI * r * r;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment