(Java) Java selection structure. Write a Java program that reads in a temperatur
ID: 3748606 • Letter: #
Question
(Java) Java selection structure.
Write a Java program that reads in a temperature in either degrees Fahrenheit,
Celsius, or Kelvin and converts the temperature to the other two formats. Your program will ask
for a single character representing the degree to be converted (F, C, K for the 3 types of
measurements) and a number representing the temperature. If the input temperature code is not
one of F, C, or K, issue an error message and end the code. If the input temperature value is not
within -700 to 700 degrees, inclusive, issue an error message and end the code.
Tempature Conversion:
C = (F - 32) * 5/9
K = (F + 459.67) * 5/9
F = C * 9/5 + 32
K = (9/5 * C + 491.67) * 5/9
F = 9/5 * K – 459.67
C = (491.67 – 9/5 * K) * 5 / 9
SAMPLE RUN:
Enter the degree conversion code: X
INVALID code
Enter the degree conversion code: F
Enter the temperature value in degrees Fahrenheit: 900
INVALID value for temperature
Enter the degree conversion code: F
Enter the temperature value in degrees Fahrenheit: 100
Temperature in degrees Celsius: 37.77 Celsius
Temperature in degrees Kelvin: 310.92 Kelvin
Enter the degree conversion code: K
Enter the temperature value in degrees Kelvin: 100
Temperature in degrees Celsius: -173.15 Celsius
Temperature in degrees Kelvin: -279.67 Fahrenheit
Explanation / Answer
import java.util.*;
class converter {
public static void main(String[] args) {
double F,C,K;
char c;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the degree conversion code: ");
c=sc.next().charAt(0);
switch(c)
{
case 'F':
System.out.println("Enter the temperature value in degrees Fahrenheit: ");
F=sc.nextInt();
if(F>700||F<-700){
System.out.println("INVALID value for temperature");
break;
}
System.out.println("Temperature in degrees Celsius: "+ (F - 32) * 5/9 +" Celsius");
System.out.println("Temperature in degrees Kelvin: "+ (F + 459.67) * 5/9+" Kelvin");
break;
case 'K':
System.out.println("Enter the temperature value in degrees Kelvin: ");
K=sc.nextInt();
if(K>700||K<-700){
System.out.println("INVALID value for temperature");
break;
}
System.out.println("Temperature in degrees Celsius: "+ (K-273.15) +" Celsius");
System.out.println("Temperature in degrees Fahrenheit: "+ ((K*9/5)-459.67) +" Fahrenheit");
break;
case 'C':
System.out.println("Enter the temperature value in degrees Celsius: ");
C=sc.nextInt();
if(C>700||C<-700){
System.out.println("INVALID value for temperature");
break;
}
System.out.println("Temperature in degrees Fahrenheit: "+ (C * 9/5 + 32)+" Fahrenheit");
System.out.println("Temperature in degrees Kelvin: "+ (C+273.15)+" Kelvin");
break;
default:
System.out.println("INVALID code");
break;
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.