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
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; } }
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); } }