Untitled
unknown
plain_text
2 years ago
1.5 kB
1
Indexable
public class Sphere { double diameter; public Sphere(double diameter) { super(); this.diameter = diameter; } public double getDiameter() { return diameter; } public void setDiameter(double diameter) { this.diameter = diameter; } // calculate volume and return the volume public double calcVolume() { double radius = this.diameter /2; /* * If you are a beginner then declare like this * * double volume = 4/3 * 3.1415* (radius * radius * radius); * * Same output will come * */ double volume = ( 4/3 * Math.PI * Math.pow(radius, 3)); return volume; } // calclate surface and return the value public double calcSurfaceArea() { double radius = this.diameter /2; // If you strange to Mathi.PI function then replace Math.PI with 3.1415 double surface = 4 * Math.PI * (radius * radius); return surface; } /*Here we are using format for the string to get the decimal place with 3. * %f indicates the float value if we give %.2f it gives 2 decimal place. Here we need 3 decimal * places so It should be like %.3f * * this refers to current object instance variable * */ public String toString() { return String.format("Sphere with diameter : %.3f \t Volume : %.3f \t Surface : %.3f",this.diameter, this.calcVolume(),this.calcSurfaceArea()); } public static void main(String[] args) { Sphere sphere = new Sphere(6); System.out.println(sphere); // it calls automatically toString method. No need to call explicitly Sphere sphere2 = new Sphere(12); System.out.println(sphere2); } }
Editor is loading...