Programming and Problem Solving with Java

(やまだぃちぅ) #1
9.2 Additional Control Statements | 447

1.In the syntax template, Init and Update are optional. If you omit Update, the ter-
mination condition is not automatically updated.
2.According to the syntax template, Expression—the continuation condition—is
optional, as shown here:
for ( ; ; )
outFile.println("Hi");
If you omit it, the expression is assumed to be the value true, creating an infinite
loop.
3.Init can be a declaration with initialization:
for(int count = 1; count <= 20; count++)
outFile.println("Hi");

In the last example, the variable counthas local scope, even though no braces in the
code explicitly create a block. The scope of countextends only to the end of the forstatement.
Like any local variable,countis inaccessible outside its scope (that is, outside the forstate-
ment). Because countis local to the for statement, it’s possible to write code like this:


for (int count = 1; count <= 20; count++)
outFile.println("Hi");
for (int count = 1; count <= 100; count++)
outFile.println("Ed");


This code does not generate a compile-time error (such as “MULTIPLY DEFINED IDENTI-
FIER”). Instead, we have declared two distinct variables named count, each of which remains
local to its own forstatement.
The syntax for Init and Update allows them to have multiple parts, separated by com-
mas. All of the parts execute as if they form a block of statements. For example, it is some-
times useful to have a second variable in a loop that is a multiple of the iteration counter.
The following loop has two variables: one that counts by one and is used as the loop control
variable and another that counts by five.


for (int count = 1, int byFives = 5; count <= n; count++, byFives = count 5)
outFile.println("Count = "+ count + "
5 = "+ byFives);


If n is 7, this loop produces the following output:


Count = 1 5 = 5
Count = 2
5 = 10
Count = 3 5 = 15
Count = 4
5 = 20
Count = 5 5 = 25
Count = 6
5 = 30
Count = 7 * 5 = 35

Free download pdf