Java Reference
In-Depth Information
Let's try out a sample of the contents of the class Math in an example to make sure we know how they
are used.
Try It Out - The Math Class
The following program will calculate the radius of a circle in feet and inches, given that it has an area of
100 square feet:
public class MathCalc {
public static void main(String[] args) {
// Calculate the radius of a circle
// which has an area of 100 square feet
double radius = 0.0;
double circleArea = 100.0;
int feet = 0;
int inches = 0;
radius = Math.sqrt(circleArea/Math.PI);
feet = (int)Math.floor(radius); // Get the whole feet and nothing but the feet
inches = (int)Math.round(12.0*(radius - feet));
System.out.println("The radius of a circle with area " + circleArea +
" square feet is\n " +
feet + " feet " + inches + " inches");
}
}
Save the program as MathCalc.java . When you compile and run it, you should get:
The radius of a circle with area 100.0 square feet is
5 feet 8 inches
How It Works
The first calculation, after defining the variables we need, uses the sqrt() method to calculate the
radius. Since the area of a circle with radius r is given by the formula
,
and we specify the argument to the sqrt() method as the expression circleArea/Math.PI , where
Math.PI references the value of
π
r 2 , the radius must be
√(
area/
π)
. The result is in feet as a double value. To get the number of whole
feet we use the floor() method. Note that the cast to int is essential in this statement otherwise you
will 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 int for you automatically because the process
potentially loses information.
π
Finally, we 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.
Note how we output the result. We specify the combination (or concatenation) of strings and variables
as an argument to the println() method. The statement is spread over two lines for convenience
here. The \n in the output specifies a newline character, so the output will be 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 typing it 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 we'll look into now.
Search WWH ::




Custom Search