Java Reference
In-Depth Information
The following loop prints the values from 1 to 5. Each iteration
through the loop prints one value, then increments the counter.
KEY CONCEPT
A
while
statement executes the
same statement until its condition
becomes false.
int
count = 1;
while
(count <= 5)
{
System.out.println (count);
count++;
}
Note that the body of the
while
loop is a block containing two statements. The
entire block is repeated on each iteration of the loop.
Let's look at another program that uses a
while
loop. The
Average
program
shown in Listing 5.7 reads a series of integer values from the user, sums them up,
and computes their average.
We don't know how many values the user may enter, so we need to have a way
to indicate that the user has finished entering numbers. In this program, we desig-
nate zero to be a
sentinel value
that indicates the end of the input. The
while
loop
continues to process input values until the user enters zero. This assumes that zero
LISTING 5.7
//********************************************************************
// Average.java Author: Lewis/Loftus
//
// Demonstrates the use of a while loop, a sentinel value, and a
// running sum.
//********************************************************************
import
java.text.DecimalFormat;
import
java.util.Scanner;
public class
Average
{
//-----------------------------------------------------------------
// Computes the average of a set of values entered by the user.
// The running sum is printed as the numbers are entered.
//-----------------------------------------------------------------
public static void
main (String[] args)
{
int
sum = 0, value, count = 0;
double
average;
Scanner scan =
new
Scanner (System.in);
Search WWH ::
Custom Search