Java Reference
In-Depth Information
The next calculation uses the sqrt() method to calculate the radius. Because the area of a circle with
radius r is given by the formula π r 2 , the radius must be , so you specify the argument to the
sqrt() method as the expression pondArea/Math.PI , where Math.PI references the value of π that is
defined in the Math class:
radius = Math.sqrt(pondArea/Math.PI);
The result is in feet as a value of type double .
To get the number of whole feet you use the floor() method:
feet = (int)Math.floor(radius); // Get the whole feet and nothing
but the feet
Note that the cast to type int of the value that is produced by the floor() method is essential in this
statement; otherwise, you get an error message from the compiler. The value returned from the floor()
method is type double , and the compiler will not cast this to type int automatically because the process
potentially loses information.
Finally, you get the number of inches by subtracting the value for whole feet from the original radius,
multiplying the fraction of a foot by 12 to get the equivalent inches, and then rounding the result to the
nearest integer using the round() method:
inches = (int)Math.round(inchesPerFoot*(radius - feet)); // Get the
inches
To output the result, you specify a combination (or concatenation) of strings and variables as an argument
to the two println() method calls:
System.out.println(
"To hold " + fishCount + " fish averaging " +
fishLength +
" inches long you need a pond with an area of \n" +
pondArea + " square feet.");
System.out.println("The radius of a pond with area " + pondArea +
" square feet is " +
feet + " feet " + inches + " inches.");
Each statement is spread over three lines for convenience here. The \n that appears in the first output
statement specifies a newline character, so the output is on two lines. Any time you want the next bit of
output to begin a new line, just add \n to the output string. You can't enter a newline character just by
pressing Enter because when you do that the cursor just moves to the next line. That's why it's specified
as \n . There are other characters like this that you cannot enter directly that are covered a little later in
this chapter.
Importing the Math Class Methods
It would be a lot more convenient if you were able to avoid having to qualify the name of every method in
the Math class that you use with the class name. The code would be a lot less cluttered if you could write
floor(radius) instead of Math.floor(radius) , for example. Well, you can. All you need to do is put the
following statement at the beginning of the source file:
import static java.lang.Math.*; // Import static class members
Search WWH ::




Custom Search