Java Reference
In-Depth Information
A
:
In general, use an
if-else-if
ladder when the conditions controlling the selection pro-
cess do not rely upon a single value. For example, consider the following
if
-
else
-
if
sequence:
This sequence cannot be recoded into a
switch
because all three conditions involve differ-
ent variables—and differing types. What variable would control the
switch
? Also, you
will need to use an
if
-
else
-
if
ladder when testing floating-point values or other objects that
are not of types valid for use in a
switch
expression.
The
initialization
is usually an assignment statement that sets the initial value of the
loop
control variable
, which acts as the counter that controls the loop. The
condition
is a
Boolean expression that determines whether or not the loop will repeat. The
iteration
ex-
pression defines the amount by which the loop control variable will change each time the
loop is repeated. Notice that these three major sections of the loop must be separated by
semicolons. The
for
loop will continue to execute as long as the condition tests true. Once
the condition becomes false, the loop will exit, and program execution will resume on the
statement following the
for
.
The following program uses a
for
loop to print the square roots of the numbers between
1 and 99. It also displays the rounding error present for each square root.