CS110 Solution Ball of Twine


NOTE: Constants should not be declared within a method. Use uppercase for constant identifiers.

 

import java.util.Scanner;

 

public class Twine {

 

        // DECLARE CONSTANTS

        static final int FEET_PER_POUND = 350;

        static final int FEET_PER_MILE = 5280;

 

        public static void main(String[] args) {

 

                // DECLARE VARIABLES

                double radius; // THE RADIUS OF THE SPHERICAL BALL IN FEET.

                double density; // THE DENSITY OF THE SPHERICAL BALL IN POUNDS PER CUBIC FEET.

                double volume; // THE VOLUME OF A SPHERE.

                double weight; // THE WEIGHT OF THE BALL IN POUNDS

                double length; // THE LENGTH OF THE BALL IN MILES

 

                // DISPLAY THE PROGRAM OBJECTIVE TO THE USER.

                System.out.println("The largest ball of twine is located in Cawker City, Kansas.");

                System.out.println("This program will calculate the weight of the ball and the number ");

                System.out.println("of miles the twine would reach if it were unrolled. ");

 

                // PROMPT THE USER FOR RADIUS AND DENSITY OF THE BALL

                Scanner in = new Scanner(System.in);

                System.out.print("Enter the radius of the ball of twine in feet : ");

                radius = in.nextDouble();

                System.out.print("Enter the density of the ball of twine in (pounds/cubic feet) : ");

                density = in.nextDouble();

 

                // COMPUTE WEIGHT = DENSITY * VOLUME

                // VOLUME OF A SPHERE is 4/3 π radius3

                // COMBINING THESE TWO FORMULAS GIVES THE FORMULA FOR WEIGHT

                volume = 4.0/ 3.0 * Math.PI * (Math.pow(radius, 3.0));

                weight = density * volume;

 

                // COMPUTE THE NUMBER OF MILES THE TWINE WILL REACH IF IT WERE UNROLLED

                length = FEET_PER_POUND * weight / FEET_PER_MILE;

 

                // DISPLAY THE WEIGHT AND LENGTH OF THE BALL WITH THREE DECIMAL PLACES

                System.out.print("\nThe world's largest ball of twine weights ");

                System.out.printf("%.3f", weight);

                System.out.print(" pounds and is ");

                System.out.printf("%.1f", length);

                System.out.print(" miles long. \n\n");

        }

}