Question:
Write a Temperature class that will hold a temperature in Fahrenheit and provide methods to convert to Celsius and kelvin.
Code:
import java.util.Scanner; public class TemperatureTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter Fahrenheit temperature: "); double ftemp = sc.nextDouble(); Temperature temp = new Temperature(ftemp); System.out.println("The temperature in Fahrenheit is " + temp.getFahrenheit()); System.out.println("The temperature in Celsius is " + temp.getCelsius()); System.out.println("The temperature in Kelvin is " + temp.getKelvin()); } } class Temperature { double ftemp; Temperature(double ftemp) { this.ftemp = ftemp; } double getFahrenheit(){ return ftemp; } double getCelsius(){ return ((double)5/9*(ftemp-32)); } double getKelvin(){ return (((double)5/9*(ftemp-32))+273); } }
Output:
$ java TemperatureTest Enter Fahrenheit temperature: -40 The temperature in Fahrenheit is -40.0 The temperature in Celsius is -40.0 The temperature in Kelvin is 233.0