The following code snippet shows the calculation of volume and surface area of a sphere. The calculations are each performed in separate functions.
import java.util.Scanner;
class VolumeSurfaceBall {
static double getVolume(double r) {
// Math.pow(base, exponent): Returns base raised to the power exponent
return (4 * Math.PI * Math.pow(r, 3)) / 3;
}
static double getSurfaceArea(double r) {
return 4 * Math.PI * Math.pow(r, 2);
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
double r, area, volume;
System.out.print("Please enter radius: ");
r = reader.nextDouble();
reader.close();
area = getSurfaceArea(r);
volume = getVolume(r);
System.out.println("Volume: " + String.format("%1.2f", volume));
System.out.println("Surface Area: " + String.format("%1.2f", area));
}
}
Please enter radius: 2.5
Volume: 65.45
Surface Area: 78.54