System, but they may not be reproduced for publication



Yüklə 83 Mb.
Pdf görüntüsü
səhifə18/82
tarix19.04.2023
ölçüsü83 Mb.
#106251
1   ...   14   15   16   17   18   19   20   21   ...   82
Java A Beginner’s Guide, Eighth Edition ( PDFDrive )

statement sequence
}
Ask the Expert
Q
: Under what conditions should I use an if­else­if ladder rather than a
switch when coding a multiway branch?
A
: In general, use an if­else­if ladder when the conditions controlling the
selection process 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 different 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
expression 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.
Notice that the rounding error is computed by squaring the square root of each


number. This result is then subtracted from the original number, thus yielding the
rounding error.
The for loop can proceed in a positive or negative fashion, and it can change the loop
control variable by any amount. For example, the following program prints the
numbers 100 to –95, in decrements of 5:
An important point about for loops is that the conditional expression is always tested
at the top of the loop. This means that the code inside the loop may not be executed at
all if the condition is false to begin with. Here is an example:
This loop will never execute because its control variable, count, is greater than 5 when
the loop is first entered. This makes the conditional expression, count < 5, false from
the outset; thus, not even one iteration of the loop will occur.
SOME VARIATIONS ON THE FOR LOOP
The for is one of the most versatile statements in the Java language because it allows a
wide range of variations. For example, multiple loop control variables can be used.
Consider the following program:
The output from the program is shown here:


Here, commas separate the two initialization statements and the two iteration
expressions. When the loop begins, both i and j are initialized. Each time the loop
repeats, i is incremented and j is decremented. Multiple loop control variables are often
convenient and can simplify certain algorithms. You can have any number of
initialization and iteration statements, but in practice, more than two or three make the
for loop unwieldy.
The condition controlling the loop can be any valid Boolean expression. It does not
need to involve the loop control variable. In the next example, the loop continues to
execute until the user types the letter S at the keyboard:
MISSING PIECES
Some interesting for loop variations are created by leaving pieces of the loop definition
empty. In Java, it is possible for any or all of the initialization, condition, or iteration
portions of the for loop to be blank. For example, consider the following program:


Here, the iteration expression of the for is empty. Instead, the loop control variable i is
incremented inside the body of the loop. This means that each time the loop repeats, i
is tested to see whether it equals 10, but no further action takes place. Of course, since i
is still incremented within the body of the loop, the loop runs normally, displaying the
following output:
In the next example, the initialization portion is also moved out of the for:
In this version, i is initialized before the loop begins, rather than as part of the for.
Normally, you will want to initialize the loop control variable inside the for. Placing the
initialization outside of the loop is generally done only when the initial value is derived


through a complex process that does not lend itself to containment inside the for
statement.
The Infinite Loop
You can create an infinite loop (a loop that never terminates) using the for by leaving
the conditional expression empty. For example, the following fragment shows the way
many Java programmers create an infinite loop:
This loop will run forever. Although there are some programming tasks, such as
operating system command processors, that require an infinite loop, most “infinite
loops” are really just loops with special termination requirements. Near the end of this
chapter, you will see how to halt a loop of this type. (Hint: It’s done using the break
statement.)
LOOPS WITH NO BODY
In Java, the body associated with a for loop (or any other loop) can be empty. This is
because a null statement is syntactically valid. Body­less loops are often useful. For
example, the following program uses one to sum the numbers 1 through 5:
The output from the program is shown here:


Notice that the summation process is handled entirely within the for statement, and no
body is needed. Pay special attention to the iteration expression:
Don’t be intimidated by statements like this. They are common in professionally
written Java programs and are easy to understand if you break them down into their
parts. In other words, this statement says, “Add to sum the value of sum plus i, then
increment i.” Thus, it is the same as this sequence of statements:
DECLARING LOOP CONTROL VARIABLES INSIDE
THE FOR LOOP
Often the variable that controls a for loop is needed only for the purposes of the loop
and is not used elsewhere. When this is the case, it is possible to declare the variable
inside the initialization portion of the for. For example, the following program
computes both the summation and the factorial of the numbers 1 through 5. It declares
its loop control variable i inside the for.
When you declare a variable inside a for loop, there is one important point to
remember: the scope of that variable ends when the for statement does. (That is, the
scope of the variable is limited to the for loop.) Outside the for loop, the variable will
cease to exist. Thus, in the preceding example, i is not accessible outside the for loop. If


you need to use the loop control variable elsewhere in your program, you will not be
able to declare it inside the for loop.
Before moving on, you might want to experiment with your own variations on the for
loop. As you will find, it is a fascinating loop.
THE ENHANCED FOR LOOP
There is another form of the for loop, called the enhanced for. The enhanced for
provides a streamlined way to cycle through the contents of a collection of objects, such
as an array. The enhanced for loop is discussed in 
Chapter 5
, after arrays have been
introduced.
THE WHILE LOOP
Another of Java’s loops is the while. The general form of the while loop is
while(conditionstatement;
where statement may be a single statement or a block of statements, and condition
defines the condition that controls the loop. The condition may be any valid Boolean
expression. The loop repeats while the condition is true. When the condition becomes
false, program control passes to the line immediately following the loop.
Here is a simple example in which a while is used to print the alphabet:
Here, ch is initialized to the letter a. Each time through the loop, ch is output and then


incremented. This process continues until ch is greater than z.
As with the for loop, the while checks the conditional expression at the top of the loop,
which means that the loop code may not execute at all. This eliminates the need for
performing a separate test before the loop. The following program illustrates this
characteristic of the while loop. It computes the integer powers of 2, from 0 to 9.
The output from the program is shown here:
Notice that the while loop executes only when e is greater than 0. Thus, when e is zero,
as it is in the first iteration of the for loop, the while loop is skipped.


Ask the Expert
Q
: Given the flexibility inherent in all of Java’s loops, what criteria
should I use when selecting a loop? That is, how do I choose the right
loop for a specific job?
A
: Use a for loop when performing a known number of iterations based on the
value of a loop control variable. Use the do­while when you need a loop that will
always perform at least one iteration. The while is best used when the loop will
repeat until some condition becomes false.
THE DO-WHILE LOOP
The last of Java’s loops is the do­while. Unlike the for and the while loops, in which
the condition is tested at the top of the loop, the do­while loop checks its condition at
the bottom of the loop. This means that a do­while loop will always execute at least
once. The general form of the do­while loop is
do {

Yüklə 83 Mb.

Dostları ilə paylaş:
1   ...   14   15   16   17   18   19   20   21   ...   82




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©genderi.org 2024
rəhbərliyinə müraciət

    Ana səhifə