Problem:
Design and implement a class called Sphere that contains instance data that represents the sphere’s diameter. Define the Sphere constructor to accept and initialize the diameter, and include getter and setter methods for the diameter. Include methods that calculate and return the volume(4/3*PI*r^3) and surface area(4*PI*r^2) of the sphere. Include a toString method that returns a one-line description of the sphere. Create a driver class called MultiSphere, whose main method instantiates and updates several Sphere objects.
Solution:
//Quick review: a class is like a complex variable
public class Sphere
{
private int diameter;
private double area;
private double volume;
public Sphere(int diameter)
this.diameter = diameter;
setSphereVolume();
setSphereArea();
}
public void setSphereDiameter(int diameter)
{
this.diameter = diameter;
}
public int getSphereDiameter()
{
return diameter;
}
public void setSphereVolume()
{
volume = Math.PI * (4.0/3.0) *
Math.pow((double)diameter/2.0,3);
}
public double getSphereVolume()
{
return volume;
}
public double getSphereArea()
{
return area;
}
public void setSphereArea()
{
area = Math.PI * 4.0 *
Math.pow((double) diameter/2.0,2);
}
public String toString()
{
String info1 = Integer.toString(diameter);
String info2 = Double.toString(area);
String info3 = Double.toString(volume);
return "Diameter: " +
info1 + "\t" + "Area: " + info2 + "\t" +
"Volume: " + info3 + "\t";
}
public static void main (String[] args)
{
Sphere sphere1 = new Sphere(4);
Sphere sphere2 = new Sphere(9);
Sphere sphere3 = new Sphere(13);
//Time to play around with the methods
sphere1.setSphereDiameter(7);
System.out.println
(sphere1.getSphereVolume());
System.out.println
(sphere1.getSphereArea());
System.out.println
(sphere1.getSphereDiameter());
System.out.println(sphere1);
System.out.println();
System.out.println(sphere2.getSphereVolume());
System.out.println(sphere2.getSphereArea());
System.out.println(sphere2.getSphereDiameter());
System.out.println(sphere2);
System.out.println();
System.out.println(sphere3.getSphereVolume());
System.out.println(sphere3.getSphereArea());
System.out.println(sphere3.getSphereDiameter());
System.out.println(sphere3);
}
}
No comments :
Post a Comment