Java Reference
In-Depth Information
Suppose that the following data is in the file Ch5_LoopWithBugsData.txt :
87 78 83 94
23 89 92 70
92 78 34 56
The objective is to find the sum of the numbers in each line. For each line, output the
numbers together with their sum. Let us consider the following program:
import java.io.*;
import java.util.*;
public class LoopWithBugsData1
{
public static void main(String[] args)
throws FileNotFoundException
{
int i;
int j;
int sum;
int num;
Scanner infile =
new Scanner( new FileReader("Ch5_LoopWithBugsData.txt"));
for (i = 1; i <= 4; i++)
{
sum = 0;
for (j = 1; j <= 4; j++)
{
num = infile.nextInt();
System.out.print(num + " ");
sum = sum + num;
}
System.out.println("sum = " + sum);
}
}
}
Sample Run:
87 78 83 94 sum = 342
23 89 92 70 sum = 274
92 78 34 56 sum = 260
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at LoopWithBugsData1.main(LoopWithBugsData1.java:23)
The Sample Run shows that there is a bug in the program because after correctly producing
the three lines of output, the program crashes with error messages. (This is an example of a
Search WWH ::




Custom Search