Java Reference
In-Depth Information
SR 3.19 Assuming that a Random object has been created called generator ,
write expressions that generate each of the following ranges of inte-
gers, including the endpoints. Use the version of the nextInt method
that accepts a single integer parameter.
a. 0 to 30
b. 10 to 19
c. −5 to 5
3.5 The Math Class
The Math class provides a large number of basic mathematical functions that are
often helpful in making calculations. The Math class is defined in the java.lang
package of the Java standard class library. Figure 3.5 lists several of its methods.
All the methods in the Math class are static methods (also called class methods ),
which means they can be invoked through the name of the class in which they are
defined, without having to instantiate an object of the class first. Static methods
are discussed further in Chapter 6.
The methods of the Math class return values, which can be used
in expressions as needed. For example, the following statement com-
putes the absolute value of the number stored in total , adds it to
the value of count raised to the fourth power, and stores the result
in the variable value :
KEY CONCEPT
All methods of the Math class are
static, meaning they are invoked
through the class name.
value = Math.abs(total) + Math.pow(count, 4);
Note that you can pass an integer value to a method that accepts a double
parameter. This is a form of assignment conversion, which was discussed in
Chapter 2.
The Quadratic program, shown in Listing 3.3, uses the Math class to compute
the roots of a quadratic equation. Recall that a quadratic equation has the fol-
lowing general form:
ax 2 + bx + c
The Quadratic program reads values that represent the coefficients in a qua-
dratic equation (a, b, and c), and then evaluates the quadratic formula to deter-
mine the roots of the equation. The quadratic formula is:
VideoNote
Example using the Random
and Math classes.
-b _
-4ac
2a
b 2
roots =
 
Search WWH ::




Custom Search