Java Reference
In-Depth Information
EXAMPLE 5-21
Consider the following data residing in a file:
65 78 65 89 25 98 -999
87 34 89 99 26 78 64 34 -999
23 99 98 97 26 78 100 63 87 23 -999
62 35 78 99 12 93 19 -999
The number -999 at the end of each line acts as a sentinel and, therefore, it is not part of
the data. Our objective is to find the sum of the numbers in each line and output the sum.
Moreover, assume that this data is to be read from a file, say, Exp_5_21.txt . We assume
that the input file has been opened using the input file stream variable inFile .
This particular data set has four lines of input. So we can use a for loop or a counter-
controlled while loop to process each line of data. Let us use a for loop to process these
four lines. The for loop takes the following form:
5
for (counter = 0; counter < 4; counter++;)
//Line 1
{
//Line 2
//process the line
//output the sum
}
Let us now concentrate on processing a line. Each line has a varying number of data
items. For example, the first line has 6 numbers, the second line has 8 numbers, and so
on. Because each line ends with -999 , we can use a sentinel-controlled while loop to
find the sum of the numbers in each line. Remember how a sentinel-controlled loop
works. Consider the following while loop:
sum = 0;
//Line 3
num = inFile.nextInt();
//Line 4
while (num != -999)
//Line 5
{
//Line 6
sum = sum + num;
//Line 7
num = inFile.nextInt();
//Line 8
}
//Line 9
The statement in Line 3 initializes sum to 0 , and the statement in Line 4 reads and stores the
first number of the line into num .The logical expression , num != -999 , in Line 5,
checks whether the number is -999 . If num is not -999 , the statements in Lines 7 and 8
execute. The statement in Line 7 updates the value of sum ; the statement in Line 8 reads and
stores the next number into num . The loop continues to execute as long as num is not -999 .
It now follows that the nested loop to process the data is as follows (assuming that all
variables are properly declared):
for (counter = 0; counter < 4; counter++;)
//Line 1
{
//Line 2
sum = 0;
//Line 3
num = inFile.nextInt();
//Line 4
Search WWH ::




Custom Search