Java Reference
In-Depth Information
Debugging: Understanding Logic Errors and
Debugging with print or println Statements
In the debugging section of Chapter 2, we illustrated how to understand and correct
syntax errors. As we have seen, syntax errors are reported by the compiler, and the
compiler not only reports syntax errors, it also gives some explanation about the errors.
On the other hand, logic errors are typically not caught by the compiler except the trivial
ones such as using a variable without properly initializing it. In this section, we illustrate
how to spot and correct logic errors using print statements. Suppose that we want
to write a program that takes as input the temperature in Fahrenheit and output
the equivalent temperature in Celsius. The formula to convert the temperature is:
Celsius ¼ 5/9*(Fahrenheit - 32). So consider the following program.
import java.util.*;
DEBUGGING
3
//Line 1
public class LogicError1
//Line 2
{
//Line 3
static Scanner console = new Scanner(System.in);
//Line 4
public static void main(String [] args)
//Line 5
{
//Line 4
int fahrenheit;
//Line 6
int celsius;
//Line 7
System.out.print("Enter temperature in "
+ "Fahrenheit: ");
//Line 8
fahrenheit = console.nextInt();
//Line 9
System.out.println();
//Line 10
celsius = 5 / 9 * (fahrenheit - 32);
//Line 11
System.out.println(fahrenheit + " degree F = "
+ celsius + " degree C.");
//Line 12
}
//Line 13
}
//Line 14
Sample Run 1: The user input is shaded.
Enter temperature in Fahrenheit: 32
32 degree F = 0 degree C.
Sample Run 2: The user input is shaded.
Enter temperature in Fahrenheit: 110
110 degree F = 0 degree C.
The result shown in the first calculation looks correct. However, the result in the second
calculation is clearly not correct even though the same formula is used, because 110 degree
F ¼ 43 degree C. Thus, the value of celsius calculated in Line 10 is incorrect. Now the
value of celsius is given by the expression 5 / 9 * (fahrenheit - 32) . So we should look
 
Search WWH ::




Custom Search