Java Reference
In-Depth Information
If you do not want to use such a debugging facility, you can trace variables by
inserting some temporary output statements in your program. For example, the
following code compiles but still contains an error:
int n = 10;
int sum = 10;
while (n > 1)
{
sum = sum + n;
n--;
}
System.out.println("The sum of the integers 1 to 10 is " + sum);
To find out what is wrong, you can trace the variables n and sum by inserting output
statements as follows:
int n = 10;
int sum = 10;
while (n > 1)
{
System.out.println("At the beginning of the loop: n = " + n);
//trace
System.out.println("At the beginning of the loop: sum = " + sum);
//trace
sum = sum + n;
n--;
System.out.println("At the end of the loop: n = " + n); //trace
System.out.println("At the end of the loop: sum = " + sum);
//trace
}
System.out.println("The sum of the integers 1 to 10 is " + sum);
The first four lines of the execution are as follows:
At the beginning of the loop: n = 10
At the beginning of the loop: sum = 10
At the end of the loop: n = 9
At the end of the loop: sum = 20
We can immediately see that something is wrong. The variable sum has been set to 20.
Since it was initialized to 10, it is set to 10 + 10, which is incorrect if we want to sum
the numbers from 1 to 10. There are several ways to correct the problem. One solution
is given as the answer to Self-Test Exercise 40.
General Debugging Techniques
Tracing errors can sometimes be a difficult and time-consuming task. It is not
uncommon to spend more time debugging a piece of code than it took to write the code
in the first place. If you are having difficulties finding the source of your errors, then
there are some general debugging techniques to consider.
Examine the system as a whole and do not assume that the bug occurs in one
particular place. If the program is giving incorrect output values, then you should
 
Search WWH ::




Custom Search