Java Reference
In-Depth Information
run (execution) time error. That is, the program compiled correctly, but crashed during
execution.) The last line of output shows that the error is in line 23 of the code, which is the
input statement:
num = infile.nextInt();
. The program is trying to read data from the
input file, but there is no more input in the file. At this point the value of the outer loop
variable
i
is
4
. Clearly, there is a bug in the program and we must fix the code. Some
programmers, especially some beginners, address the symptom of the problem by adding a
software patch. A beginning programmer might fix the code by adding a software patch as
shown in the following modified program:
import
java.io.*;
import
java.util.*;
public class
LoopWithBugsData2
{
5
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;
if
(i != 4)
{
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
Clearly, the program is working correctly now.
Search WWH ::
Custom Search