Java Reference
In-Depth Information
3.4
Debugging
The road to wisdom? — Well, it's plain and simple to express: Err, and err,
and err again, but less, and less, and less.
PIET HEIN
Loop Bugs
There is a pattern to the kinds of mistakes you are most likely to make when program-
ming with loops. Moreover, there are some standard techniques you can use to locate
and fix bugs in your loops.
The two most common kinds of loop errors are unintended infinite loops and off-
by-one errors. We have already discussed infinite loops, but we still need to consider
off-by-one errors.
If your loop has an off-by-one error , that means the loop repeats the loop body
one too many or one too few times. These sorts of errors can result from carelessness in
designing a controlling Boolean expression. For example, if you use less-than when
you should use less-than-or-equal, this can easily make your loop iterate the body the
wrong number of times.
Use of == to test for equality in the controlling Boolean expression of a loop can
often lead to an off-by-one error or an infinite loop. This sort of equality testing can
work satisfactorily for integers and characters, but is not reliable for floating-point
numbers. This is because the floating-point numbers are approximate quantities, and
== tests for exact equality. The result of such a test is unpredictable. When comparing
floating-point numbers, always use something involving less-than or greater-than,
such as <= ; do not use == or != . Using == or != to test floating-point numbers can pro-
duce an off-by-one error or an unintended infinite loop or even some other type of
error. Even when using integer variables, it is best to avoid using == and != and to
instead use something involving less-than or greater-than.
Off-by-one errors can easily go unnoticed. If a loop is iterated one too many times or one
too few times, the results might still look reasonable but be off by enough to cause trouble
later on. Always make a specific check for off-by-one errors by comparing your loop results to
results you know to be true by some other means, such as a pencil-and-paper calculation.
off-by-one
error
Tracing Variables
One good way to discover errors in a loop or any kind of code is to trace some key variables.
Tracing variables means watching the variables change value while the program is run-
ning. Most programs do not output each variable's value every time the variable changes, but
being able to see all of these variable changes can help you to debug your program.
Many IDEs (Integrated Development Environments) have a built-in utility that
lets you easily trace variables without making any changes to your program. These
debugging systems vary from one IDE to another. If you have such a debugging facil-
ity, it is worth learning how to use it.
tracing
variables
Search WWH ::




Custom Search