Difference between revisions of "Temperature Calculator"

From CompSciWiki
Jump to: navigation, search
Line 9: Line 9:
 
<br/>
 
<br/>
 
Example: User inputs "c" and "10" would result in "50f"
 
Example: User inputs "c" and "10" would result in "50f"
<br/>
 
 
<br/>
 
<br/>
  
Line 61: Line 60:
  
 
<pre> import javax.swing.*;</pre>
 
<pre> import javax.swing.*;</pre>
<br/><br/>
+
<br/>
  
 
Define your variables, we will need doubles in case of decimal results, and a string value for the unit
 
Define your variables, we will need doubles in case of decimal results, and a string value for the unit

Revision as of 12:08, 6 April 2010

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
  • output the solution followed by a c or f to denote the final units


Example: User inputs "c" and "10" would result in "50f"

Use the following formula to convert your units

F = 9C/5 + 32

 

...by students

float
Taken from http://www.flickr.com/photos/daniello/565304023/

An image or By Students section

Solution

Start by importing the swing java package.

 import javax.swing.*;


Define your variables, we will need doubles in case of decimal results, and a string value for the unit

double temperature, result;
String unit;


Next start by capturing the user input using JOptionPane. We will need to use Integer.parseInt to cast the String result to an integer for the temperature.

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"));

Code

Solution Code

Back to the Program-A-Day homepage