Java Reference
In-Depth Information
It is fine to declare i in two
nonnested blocks.
It is wrong to declare i in two
nested blocks.
public static void method1() {
int x = 1 ;
int y = 1 ;
public static void method2() {
int i = 1 ;
int sum = 0 ;
for ( int
i
= 1 ; i < 10 ; i++) {
x += i;
for ( int i = 1 ; i < 10 ; i++)
sum += i;
}
}
for ( int
i
= 1 ; i < 10 ; i++) {
y += i;
}
}
}
F IGURE 6.6
A variable can be declared multiple times in nonnested blocks, but only once in nested blocks.
Caution
Do not declare a variable inside a block and then attempt to use it outside the block.
Here is an example of a common mistake:
for ( int i = 0 ; i < 10 ; i++) {
}
System.out.println(i);
The last statement would cause a syntax error, because variable i is not defined outside
of the for loop.
6.18
What is a local variable?
Check
6.19
What is the scope of a local variable?
Point
6.10 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 4.3, 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 ))
 
 
 
Search WWH ::




Custom Search