# Sphere (Volume/Surface Area)

• October 4th, 2011, 04:47 PM
Alex L
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);   } }```
• October 4th, 2011, 06:05 PM
copeg
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);```
• October 4th, 2011, 07:31 PM
Alex L
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.
• October 4th, 2011, 09:16 PM
copeg
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);```
• October 5th, 2011, 02:51 PM
Alex L
Re: Sphere (Volume/Surface Area)
Thank you, that works a treat :)