Temperature Calculator
Back to the Program-A-Day homepage
ProblemWrite a Java program Temp, that converts celsius to fahrenheit or vice versa.
Use the following formula to convert your units: <math>F = 9C/5 + 32</math> |
Temperature Calculator | |
---|---|---|
SolutionStart 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 (Celsius) or f (Fahrenheit)") ; temperature = Integer.parseInt(JOptionPane.showInputDialog("Enter the current temperature in the units you specified")); Now we need to use conditional statements to check for each unit, one for Celsius and one for Fahrenheit. One thing to note is that because unit is a String data type, we will have to only extract the first character assuming it has be entered in correctly, this is easily accomplished using where index is the position at which the char character is at in the String. unit.charAt(int index) For each case, calculate your results and print the output using System.out. We rounded our answer to make use of the built in Math class. To round it to two decimal places or the nearest one-hundredth you have to multiply by 100 since Math.round returns an int and then divide by 100.0. Note: divide by 100.0 in order to keep the result a double, otherwise it will result in an integer if (unit.charAt(0) == 'c') { result = 9 * temperature / 5 + 32; result = Math.round(result*100)/100.0; System.out.println(temperature + " degree Celsius = " + result + " degree Fahrenheit"); } else if (unit.charAt(0) == 'f') { result = (temperature - 32) * 5 / 9; result = Math.round(result*100)/100.0; System.out.println(temperature + " degree Fahrenheit = " + result + " degree Celsius"); } To make your program more robust, you may want to use an else case for all invalid characters. else System.out.println("You entered an incorrect unit, please try again"); | ||
Code |