Java Reference
In-Depth Information
at this expression closely. To see the effect of this expression, we can separately print the values
of the two expression 5 / 9 and fahrenheit - 32 . This can be accomplished by temporarily
inserting an output statement as shown in the following program:
import java.util.*;
//Line 1
public class LogicError2
//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
System.out.println("5 / 9 = " + 5 / 9
+ "; fahrenheit - 32 = "
+ (fahrenheit - 32));
//Line 10a
celsius = 5 / 9 * (fahrenheit - 32);
//Line 11
System.out.println(fahrenheit + " degree F = "
+ celsius + " degree C.");
//Line 12
}
//Line 13
}
//Line 14
Sample Run: In this sample run, the user input is shaded.
Enter temperature in Fahrenheit: 110
5 / 9 = 0; fahrenheit - 32 = 78
110 degree F = 0 degree C.
Let us look at the sample run. We see that the value of 5 / 9 ¼ 0 and the value of
fahrenheit - 32 ¼ 78 . Because fahrenheit ¼ 110 , the value of the expression
fahrenheit - 32 is correct. Now let us look at the expression 5 / 9 . The value of
this expression is 0 . Because both the operands, 5 and 9 , of the operator / are integers,
using integer division, the value of the expression is 0 . That is, the value of the expression
5 / 9 ¼ 0 is also calculated correctly. So by the precedence of the operators, the value of
the expression 5 / 9 * (fahrenheit - 32) will always be 0 regardless of the value of
fahrenheit . So the problem is in the integer division. There are two solutions to this
problem. In the first solution, we can replace the expression 5 / 9 with 5.0 / 9 . In this
case, the value of the expression 5.0 / 9 * (fahrenheit - 32) will be a decimal
number. Because fahrenheit and celsius are int variables, we can use the cast
operators to convert this value to an integer, that is, we use the following expression:
celsius = ( int ) (5.0 / 9 * (fahrenheit - 32) + 0.5);
Search WWH ::




Custom Search