This Java program calculates and displays information about the volumes of the Earth and the Sun. It also show the ratio of their volumes. Here’s a step-by-step explanation for a novice Java programmer:
Variable Initialization:
sunRad
andearthRad
are initialized with the radii of the Sun and Earth respectively.fourOverThree
is set to the value of 4.0 divided by 3.0.sunVol
,earthVol
, andratioVol
are declared and initialized to 0.
Volume Calculation:
- Using the formula for the volume of a sphere (
V = 4/3 * π * r^3
), the program calculates the volumes of the Earth (earthVol
) and the Sun (sunVol
). Math.pow(x, y)
is used to raise a number to the power of another.
Volume Ratio Calculation:
- The program calculates the ratio of the Sun’s volume to the Earth’s volume (
ratioVol
).
Output in Words:
- The program then prints the results to the console using
System.out.println
. - The volumes of the Earth and the Sun are displayed in cubic miles, and the ratio of the Sun’s volume to the Earth’s volume is shown.
Additional Method (convertToWords
):
- To make the output more readable we have written a method called
convertToWords
. - This method takes a double value and converts it to words, appending appropriate unit names (thousand, million, etc.).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | public class Volumes { public static void main(String[] args) { // Initialize a double variable to be the sun's diameter double sunRad = 865000.0/2.0; double earthRad = 7926.4/2.0; double fourOverThree = 4.0/3.0; double sunVol = 0, earthVol = 0; // You can declare a number of variables double ratioVol = 0; // of the same type on a single line if you wish. // Find the volumes of earth and sun earthVol = fourOverThree*Math.PI*Math.pow(earthRad,3); sunVol = fourOverThree*Math.PI*Math.pow(sunRad,3); // Find the ratio of their volumes ratioVol = sunVol/earthVol; // Output the results in words System.out.println("Volume of the earth is approximately " + convertToWords(earthVol) + " cubic miles."); System.out.println("Volume of the sun is approximately " + convertToWords(sunVol) + " cubic miles."); System.out.println("The sun's volume is approximately " + convertToWords(ratioVol) + " times greater than the earth's."); } // Method to convert a double value to words private static String convertToWords(double value) { String[] units = {"", "thousand", "million", "billion", "trillion", "quadrillion"}; int i = 0; while (value >= 1000) { value /= 1000; i++; } return String.format("%.2f %s", value, units[i]); } } |