Java Reference
In-Depth Information
As discussed in Section 4.3.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. Therefore,
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 ))
Hence, a random character between any two characters ch1 and ch2 with ch1 < ch2 can be
generated as follows:
( char )(ch1 + Math.random() * (ch2 - ch1 + 1 ))
This is a simple but useful discovery. Listing 6.10 defines a class named RandomCharacter
with five overloaded methods to get a certain type of character randomly. You can use these
methods in your future projects.
L ISTING 6.10
RandomCharacter.java
1 public class RandomCharacter {
2
/** Generate a random character between ch1 and ch2 */
3
public static char getRandomCharacter( char ch1, char ch2) {
getRandomCharacter
4
return ( char )(ch1 + Math.random() * (ch2 - ch1 + 1 ));
5 }
6
7
/** Generate a random lowercase letter */
getRandomLower
CaseLetter()
8
public static char getRandomLowerCaseLetter() {
9
return getRandomCharacter( 'a' , 'z' );
10 }
11
12
/** Generate a random uppercase letter */
13
public static char getRandomUpperCaseLetter() {
getRandomUpper
CaseLetter()
14
return getRandomCharacter( 'A' , 'Z' );
15 }
16
17
/** Generate a random digit character */
18
public static char getRandomDigitCharacter() {
getRandomDigit
Character()
19
return getRandomCharacter( '0' , '9' );
20 }
21
22
/** Generate a random character */
23
public static char getRandomCharacter() {
getRandomCharacter()
24
return getRandomCharacter( '\u0000' , '\uFFFF' );
25 }
26 }
Listing 6.11 gives a test program that displays 175 random lowercase letters.
L ISTING 6.11
TestRandomCharacter.java
1 public class TestRandomCharacter {
2
/** Main method */
3
public static void main(String[] args) {
4
final int NUMBER_OF_CHARS = 175 ;
constants
5
final int CHARS_PER_LINE = 25 ;
6
7
// Print random characters between 'a' and 'z', 25 chars per line
8
for ( int i = 0 ; i < NUMBER_OF_CHARS; i++) {
 
 
Search WWH ::




Custom Search