Celsius to Fahrenheit In Java – Fahrenheit To Celsius In Java
In this article, we are going to learn the conversion of temperature
from Celsius to Fahrenheit and Fahrenheit to Celsius. In the following, we are
using a switch case to give the effect of a menu. If the user press 1 it will convert Fahrenheit
to Celsius and when the user press 2 it will convert Celsius to Fahrenheit.
We are using formula of temperature conversion as follows:
celsius = 5.0/9.0 * (fahrenheit - 32)
fahrenheit = 1.8 * celsius + 32
Source code as follows
import java.util.*;
public class TemperatureMenu
{
public static void
main(String args[])
{
Scanner sc = new
Scanner(System.in);
double celsius,
fahrenheit;
int ch; // for choice
System.out.println("1. for Farenheit to Celsius");
System.out.println("2. for Celsius to Fahrenheit");
System.out.println("Enter Your Choice : ");
ch = sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter temperature in Fahrenheit");
fahrenheit =
sc.nextDouble();
celsius = 5.0/9.0 *
(fahrenheit - 32);
System.out.println("Temperature in Celsius is =" + celsius);
break;
case 2:
System.out.println("Enter temperature in Celsius");
celsius =
sc.nextDouble();
fahrenheit = 1.8 *
celsius + 32;
System.out.println("Temperature in Fahrenheit is =" +
fahrenheit);
break;
default:
System.out.println("Wrong Choice...");
}
}
}
Output
First, run
1. for Fahrenheit to Celsius
2. for Celsius to Fahrenheit
Enter Your Choice :
1
Enter temperature in Fahrenheit
100
Temperature in Celsius is =37.77777777777778
Second run
1. for Fahrenheit to Celsius
2. for Celsius to Fahrenheit
Enter Your Choice :
2
Enter temperature in Celsius
100
Temperature in Fahrenheit is =212.0