Java Reference
In-Depth Information
5.22
True or false? The argument for trigonometric methods is an angle in radians.
Check
5.23
Point
Write an expression that obtains a random integer between 34 and 55 . Write an
expression that obtains a random integer between 0 and 999 . Write an expression that
obtains a random number between 5.5 and 55.5 . Write an expression that obtains a
random lowercase letter.
5.24
Evaluate the following method calls:
a. Math.sqrt( 4 )
b. Math.sin( 2 * Math.PI)
c. Math.cos( 2 * Math.PI)
d. Math.pow( 2 , 2 )
e. Math.log(Math.E)
f. Math.exp( 1 )
g. Math.max( 2 , Math.min( 3 , 4 ))
h. Math.rint( -2.5 )
i. Math.ceil( -2.5 )
j. Math.floor( -2.5 )
k. Math.round( -2.5f )
l. Math.round( -2.5 )
m. Math.rint( 2.5 )
n. Math.ceil( 2.5 )
o. Math.floor( 2.5 )
p. Math.round( 2.5f )
q. Math.round( 2.5 )
r. Math.round(Math.abs( -2.5 ))
5.11 Case Study: Generating Random Characters
A character is coded using an integer. Generating a random character is to generate
an integer.
Key
Point
Computer programs process numerical data and characters. You have seen many examples
that involve numerical data. It is also important to understand characters and how to process
them. This section presents an example of generating random characters.
As introduced in Section 2.17, every character has a unique Unicode between 0 and FFFF in
hexadecimal ( 65535 in decimal). To generate a random character is to generate a random integer
between 0 and 65535 using the following expression (note that since 0 <= Math.random() <
1.0 , you have to add 1 to 65535 ):
( int )(Math.random() * ( 65535 + 1 ))
Now let's consider how to generate a random lowercase letter. The Unicodes for lowercase
letters are consecutive integers starting from the Unicode for a , then that for b , c , . . . , and
z . The Unicode for a is
( int ) 'a'
Thus, a random integer between (int)'a' and (int)'z' is
( int )(( int ) 'a' + Math.random() * (( int ) 'z' - ( int ) 'a' + 1 ))
As discussed in Section 2.17.3, all numeric operators can be applied to the char operands.
The char operand is cast into a number if the other operand is a number or a character. There-
fore, the preceding expression can be simplified as follows:
'a' + Math.random() * ( 'z' - 'a' + 1 )
and a random lowercase letter is
( char )( 'a' + Math.random() * ( 'z' - 'a' + 1 ))
 
 
Search WWH ::




Custom Search