Back to the Program-A-Day homepage
Problem
Write a Java program Temp, that converts celcius to fahrenheit or vice versa. The program should:
- prompt the user for a 1-character string c (celcius) or f (fahrenheit) that tells the program which unit you are entering
- prompt the user for the temperature as an integer (2-digits max)
- output the solution followed by a c or f to note the final unit
Example: User inputs "c" and "10" would result in "50f"
Use the following formula to convert your units
F = 9C/5 + 32
|
|
...by students
Taken from http://www.flickr.com/photos/daniello/565304023/
An image or By Students section
|
Solution
The solution...
|
Code
Solution Code
import javax.swing.*;
public class Temp
{
public static void main(String[] args)
{
double temperature, result;
String unit;
unit = JOptionPane.showInputDialog("Enter the 1-character temperature you want to convert from c (Celcius) or f (Fahrenheit)") ;
temperature = Integer.parseInt(JOptionPane.showInputDialog("Enter the current temperature in the units you speficied (2-digits max)"));
if (unit.charAt(0) == 'c')
{
result = 9 * temperature / 5 + 32;
System.out.println(temperature + " degree Celcius = " + result + " degree Fahrenheit");
}
else if (unit.charAt(0) == 'f')
{
result = (temperature - 32) * 5 / 9;
System.out.println(temperature + " degree Fahrenheit = " + result + " degree Celcius");
}
}
}
|
Back to the Program-A-Day homepage