Java Reference
In-Depth Information
LISTING 2.2
Continued
5: // To convert Fahrenheit into Celsius
6: // Begin by subtracting 32
7: fah = fah - 32;
8: // Divide the answer by 9
9: fah = fah / 9;
10: // Multiply that answer by 5
11: fah = fah * 5;
12: System.out.println(fah + “ degrees Celsius\n”);
13:
14: float cel = 33;
15: System.out.println(cel + “ degrees Celsius is ...”);
16: // To convert Fahrenheit into Celsius
17: // Begin by subtracting 32
18: cel = cel * 9;
19: // Divide the answer by 9
20: cel = cel / 5;
21: // Multiply that answer by 5
22: cel = cel + 32;
23: System.out.println(cel + “ degrees Fahrenheit”);
24: }
25: }
When you compile and run this Java application, it produces the following output:
86.0 degrees Fahrenheit is ...
30.0 degrees Celsius
33.0 degrees Celsius is ...
91.4 degrees Fahrenheit
In lines 3-12 of this Java application, a temperature in Fahrenheit is converted to Celsius
using the arithmetic operators:
Line 3—The floating-point variable fah is created with a value of 86 .
n
Line 4—The current value of fah is displayed.
n
Line 5—The first of several comments explain what the program is doing. The
Java compiler ignores these comments.
n
Line 7— fah is set to its current value minus 32.
n
Line 9— fah is set to its current value divided by 9.
n
Line 11— fah is set to its current value multiplied by 5.
n
Line 12—Now that fah has been converted to a Celsius value, fah is displayed again.
n
A similar thing happens in lines 14-23 but in the reverse direction—a temperature in
Celsius is converted to Fahrenheit.
 
Search WWH ::




Custom Search