Java Reference
In-Depth Information
The next few sections describe the various forms of
while
loops.
Suppose you know exactly how many times certain statements need to be executed. For
example, suppose you know exactly how many pieces of data (or entries) need to be read. In
such cases, the
while
loop assumes the form of a counter-controlled
while
loop. (If you
know the number of iterations in advance, a
for
loop should be used.) Suppose that a set of
statements needs to be executed
N
times. You can set up a
counter
(initialized to
0
before the
while
statement) to track how many items have been read. Before executing the body of the
while
statement, the
counter
is compared with
N
.If
counter < N
, the body of the
while
statement executes. The body of the loop continues to execute until the value of
counter >=
N
. Thus, inside the body of the
while
statement, the value of
counter
increments after it
reads a new item. In this case, the
while
loop might look like the following:
5
counter = 0;
//initialize the loop control variable
while
(counter < N)
//test the loop control variable
{
.
.
.
counter++;
//update the loop control variable
.
.
.
}
If
N
represents the number of data items in a file, then the value of
N
can be determined
several ways: The program can prompt you to specify the number of items in the file; an
input statement can read the value; or you can specify the first item in the file as the number
of items in the file, so that you need not remember the number of input values (items). This
is useful if someone other than the programmer enters the data. Consider Example 5-3.
EXAMPLE 5-3
Suppose the input is:
8 9 2 3 90 38 56 8 23 89 7 2
Suppose you want to add these numbers and find their average. Consider the following
program.
//Counter-controlled while loop
import
java.util.*;
public class
CounterControlledWhileLoop
{
static
Scanner console =
new
Scanner(System.in);
Search WWH ::
Custom Search