Java Temperature Converter


 

Java Temperature Converter

In this tutorial, you will learn how to convert temperature from Celsius to Fahrenheit and vice versa.

In this tutorial, you will learn how to convert temperature from Celsius to Fahrenheit and vice versa.

Java Temperature Converter

In this tutorial, you will learn how to convert temperature from Celsius to Fahrenheit and vice versa. Here is an example where we have created three functions celcius(), fahrenheit() and display table. It prints the chart in tabular format and shows the conversion of the Fahrenheit equivalents of all Celsius temperatures from 0 to 100 degrees in 4 degree intervals and the Celsius equivalents of all Fahrenheit temperatures from 32 to 212 degrees in 10 degree intervals.

Example

import java.util.*;
import java.text.*;

class Degrees 
{
public static double fahrenheit(int temp) {
return (1.8 * temp) + 32;
}

public static double celsius(int temp) {
return (temp - 32) / 1.8;
}
public static void displayTable(){
DecimalFormat df=new DecimalFormat("##.#");
System.out.println("Celcius (C) Fahrenheit (F)");
for(int i=0;i<=100;i+=4){
System.out.println(i+"\t | "+df.format(fahrenheit(i)));
}
System.out.println("Fahrenheit (F) Celcius (C) ");
for(int i=32;i<=212;i+=10){
System.out.println(i+"\t | "+df.format(celsius(i)));
}
}

public static void main(String[] args) 
{
displayTable();
}
}

Output:

Celcius (C)   Fahrenheit (F)
0           |     32
4           |     39.2
8           |     46.4
12          |     53.6
16          |     60.8
20          |     68
24          |     75.2
28          |     82.4
32          |     89.6
36          |     96.8
40          |     104
44          |     111.2
48          |     118.4
52          |     125.6
56          |     132.8
60          |     140
64          |     147.2
68          |     154.4
72          |     161.6
76          |     168.8
80          |     176
84          |     183.2
88          |     190.4
92          |     197.6
96          |     204.8
100         |     212
Fahrenheit (F)   Celcius (C)
32          |     0
42          |     5.6
52          |     11.1
62          |     16.7
72          |     22.2
82          |     27.8
92          |     33.3
102         |     38.9
112         |     44.4
122         |     50
132         |     55.6
142         |     61.1
152         |     66.7
162         |     72.2
172         |     77.8
182         |     83.3
192         |     88.9
202         |     94.4
212         |     100

Ads