Java Reference
In-Depth Information
is not one of the valid numbers that should contribute to the average. A sentinel
value must always be outside the normal range of values entered.
Note that in the Average program, a variable called sum is used to maintain a
running sum, which means it is the sum of the values entered thus far. The variable
sum is initialized to zero, and each value read is added to and stored back into sum .
We also have to count the number of values that are entered so that after the
loop concludes we can divide by the appropriate value to compute the average.
Note that the sentinel value is not counted. Consider the unusual situation in
which the user immediately enters the sentinel value before entering any valid
values. The if statement at the end of the program avoids a divide-by-zero error.
Let's examine yet another program that uses a while loop. The WinPercentage
program shown in Listing 5.8 computes the winning percentage of a sports team
based on the number of games won.
We use a while loop in the WinPercentage program to validate the input,
meaning we guarantee that the user enters a value that we consider to be valid.
In this example, that means that the number of games won must be greater than
or equal to zero and less than or equal to the total number of games played. The
while loop continues to execute, repeatedly prompting the user for valid input,
until the entered number is indeed valid.
VideoNote
Examples using while
loops.
LISTING 5.8
//********************************************************************
// WinPercentage.java Author: Lewis/Loftus
//
// Demonstrates the use of a while loop for input validation.
//********************************************************************
import java.text.NumberFormat;
import java.util.Scanner;
public class WinPercentage
{
//-----------------------------------------------------------------
// Computes the percentage of games won by a team.
//-----------------------------------------------------------------
public static void main (String[] args)
{
final int NUM_GAMES = 12;
int won;
double ratio;
 
Search WWH ::




Custom Search