Sphere (Volume/Surface Area)

A question (not homework, a question from a book, don't worry) asks me to create a program to work out the volume and surface area of a sphere.

The surface area part works fine, it is the volume which comes up with the wrong answers. I can't see anything wrong with the formula so I assuming it must be a coding error on my part. Also feel free to criticise general coding standards. The more it hurts the more it helps ;)

Thanks

Code :

public class Sphere {
public double diameter;
private double radius, volume, surfaceArea;
public Sphere() {
diameter = 1;
}
public void setDiameter (double value) {
diameter = value;
}
public double getDiameter() {
return diameter;
}
private double radius() {
radius = diameter / 2;
return radius;
}
private double volume() {
volume = (4/3) * Math.PI * Math.pow(radius(), 3);
return volume;
}
private double surfaceArea() {
surfaceArea = 4 * Math.PI * Math.pow(radius(), 2);
return surfaceArea;
}
public String toString() {
String result = "Volume: " + Double.toString(volume()) + " Surface area: " + Double.toString(surfaceArea());
return result;
}
}

Code :

public class MultiSphere {
public static void main(String[] args) {
Sphere sph1, sph2;
sph1 = new Sphere();
sph2 = new Sphere();
sph1.setDiameter(4);
sph2.setDiameter(10);
System.out.println(sph1);
System.out.println(sph2);
}
}

Re: Sphere (Volume/Surface Area)

Be sure you are using floating point math. For instance, try out the following code:

Code :

double ratio = 4/3;
System.out.println(ratio);

Re: Sphere (Volume/Surface Area)

Thank you for pointing that out. I didn't notice it. By changing part of the code to this:

Code :

private double volume() {
volume = 1.33333333 * Math.PI * Math.pow(radius(), 3);
return volume;

The program works. I have just done some quick reading on the subject but don't really get how I can implement a solution. Could you give a pointer towards a good explanation if you know of one.

Re: Sphere (Volume/Surface Area)

Specify a floating point number by defining a double or float. The above example can be adapted for floating point math:

Code :

double ratio = 4/3d;//specifies double math
System.out.println(ratio);
ratio = 4/3f;//specifies float math
System.out.println(ratio);

Re: Sphere (Volume/Surface Area)

Thank you, that works a treat :)