Java Reference
In-Depth Information
4. Do not attempt to compute a value that is greater than the largest
permissible value or less than the smallest permissible nonzero value for
the data type.
5. Do not try to compare different data types in a conditional expression.
The Math Class
Numeric expressions in formulas are the most common use of operators in
Java, although some math functions cannot be performed with operators alone.
Figure 3-17 displays the formulas used in the Body Mass Index Calculator pro-
gram. While the first two formulas can be written with operators, the third one
needs a special method to calculate the answer.
32
// calculations
33
meters = inches / 39.36;
34
kilograms = pounds / 2.2;
35
index = kilograms / Math .pow ( meters,2 ) ;
36
FIGURE 3-17
In the first formula, inches are converted to meters by dividing them by 39.36
(line 33). Pounds are converted to kilograms by dividing by 2.2 (line 34). When
int variables, such as inches and pounds, are divided by double values such as
39.36 and 2.2, Java stores the answer as the larger data type. Meters and kilograms
thus were declared to be double in line 19 (Figure 3-9 on page 141).
The final formula for BMI is calculated by dividing kilograms by the meters
squared, which calls for an exponent. The process of raising a number to the
power of an exponent is called exponentiation . In some math notations, a caret
sign (^) is used to denote an exponent. For example, 4 ^ 2 is the same as 4 2 and
is equal to 16, and 3 ^ 4 is the same as 3 4 and is equal to 81. Even though Java
has no exponentiation operator, it easily is accomplished by using a prewritten
method from the Math class. The Math class , which is part of the java.lang
package, contains methods for a number of useful functions, such as rounding,
exponentiation, randomizing, and square roots. Methods from the Math class
have the general form shown in Table 3-9 on the next page. The table displays
only some of the many methods from the Math class; a complete listing is avail-
able in the Java API.
Search WWH ::




Custom Search