write a Java program that asks the user for a temperature (in either degrees Cel
ID: 3684726 • Letter: W
Question
write a Java program that asks the user for a temperature (in either degrees Celsius or degrees Fahrenheit). If the user entered Celsius, you will convert the temperature to Fahrenheit. If they entered Fahrenheit, you will convert the temperature to Celsius. Here is how to convert between temperature systems (be sure to not use integer division in Java so you can keep the decimal of something like 5/9): F = (9/5)*C + 32 C = (5/9)*(F-3This program should contain a single class (called Proj2) with a main method. Your program should compile and run in BlueJ. Here are some additional requirements:
-Your program should work correctly with either upper- or lower-case letters (C/c/F/f)
-You should print an error if the user enters a character other than C/c/F/f
- You should round temperatures to the nearest two decimal places
Explanation / Answer
import java.util.Scanner;
public class Temperature {
public static void main(String[] args){
Scanner console = new Scanner(System.in);
// Creating the default output message
System.out.println("Welcome to Temple Weather Channel");
System.out.println("Temperature Conversion Program");
System.out.println("");
System.out.print(" [Q1] Enter a temperature in degrees (for example 29.6): ");
double temperature = console.nextDouble();
System.out.print(" [Q2] Enter 'F' (or 'f') for Fahrenheit or 'C' (or 'c') for Celsius: ");
String option = console.next();
//Compute the logic here
double temp;
switch (option.charAt(0)) {
case 'F':
case 'f':
// the user wants converted to fahrenheit!
temp = 5 * (temperature - 32) / 9;
System.out.println(" " + temperature + " degrees " + option.toUpperCase() + " = " + temp + " degrees Celsius.");
break;
case 'C':
case 'c':
temp = (9 * temperature / 5) + 32;
System.out.println(" "+ temperature + " degrees " + option.toUpperCase() + " = " + temp + " degrees Fahrenheit.");
break;
default:
System.out.println("Unknown units - ");
System.out.println("Cannot do calculation - ");
System.out.println("Please next time enter either 'F' for Fahrenheit or 'C' for Celsius.");
break;
}
System.out.println(" Program ended.");
}
}
sample output
Welcome to Temple Weather Channel
Temperature Conversion Program
[Q1] Enter a temperature in degrees (for example 29.6): 30
[Q2] Enter 'F' (or 'f') for Fahrenheit or 'C' (or 'c') for Celsius: f
30.0 degrees F = -1.1111111111111112 degrees Celsius.
Program ended.
Welcome to Temple Weather Channel
Temperature Conversion Program
[Q1] Enter a temperature in degrees (for example 29.6): 30
[Q2] Enter 'F' (or 'f') for Fahrenheit or 'C' (or 'c') for Celsius: d
Unknown units -
Cannot do calculation -
Please next time enter either 'F' for Fahrenheit or 'C' for Celsius.
Program ended.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.