Java Reference
In-Depth Information
PROGRAMMING EXAMPLE: Temperature Conversion
Write a program that creates the GUI shown in Figure 6-9, to convert the tempera-
ture from Fahrenheit to Celsius and from Celsius to Fahrenheit.
FIGURE 6-9 GUI for the temperature conversion program
6
When the user enters the temperature in the text field adjacent to the label Temp in
Celsius: and presses the Enter key, the program displays the equivalent tempera-
ture in the text field adjacent to the label Temp in Fahrenheit: Similarly, when the
user enters the temperature in Fahrenheit and presses the Enter key, the program
displays the equivalent temperature in Celsius.
Input: Temperature in Fahrenheit or Celsius
Output: Temperature in Celsius if the input is Fahrenheit; the temperature in Fahrenheit
if the input is Celsius
Suppose that the variable celsius represents the temperature in Celsius and the
variable fahrenheit represents the temperature in Fahrenheit. If the user enters the
temperature in Fahrenheit, the formula for calculating the equivalent temperature in
Celsius is:
PROBLEM
ANALYSIS,
GUI DESIGN,
AND
ALGORITHM
DESIGN
celsius = (5.0 / 9.0) * (fahrenheit - 32)
For example, if fahrenheit is 98.6 , then:
celsius = 5.0 / 9.0 * (98.6 - 32) = 37.00
Similarly, if the user enters the temperature in Celsius, then the formula for calculat-
ing the equivalent temperature in Fahrenheit is:
fahrenheit = 9.0 / 5.0 * celsius + 32
For example, if celsius is 20 , then:
fahrenheit = 9.0 / 5.0 * 20 + 32 = 68.0
The GUI in Figure 6-9 contains a window, a container, two labels, and two text
fields. The labels and text fields are placed in the container of the window. As we did
Search WWH ::




Custom Search