Execution-Time Errors
In this lesson, we will focus on finding logical errors in a program.
We'll cover the following...
An error in the logic of a program usually goes undetected by the compiler. Rather, such errors cause problems during the program’s execution. As we indicated in the previous lesson of this debugging interlude, a logical error might or might not cause an error message during execution.
Incorrect arithmetic
The program in the previous lesson had a syntax error. The following program corrects that error by inserting the * operator between 2 and y in the computation of z. Execute this program by clicking the RUN button.
public class Debug17{public static void main(String[] args){double x = 50.5;double y = 4.8;double z = 7 / 8 * x + 2 * y;System.out.println("x is " + x + ", y is " + y + ", z is " + z);} // End main} // End Debug17
This program compiles without error, and its execution produces the following output:
x is 50.5, y is 4.8, z is 9.6
As tempting as it might be to feel successful, we should check our answer. Substituting 50.5 and 4.8 for the variables x and y, respectively, and using a calculator, we would compute 53.7875 as the value of z. The program computed 9.6. How can we be so far off? ...