In: Computer Science
Write a Temperature class that will hold a temperature in Fahrenheit, and provide methods to get the temperature in Fahrenheit, Celsius and Kelvin. The class should have the following field:
The class should have the following methods:
Use the following formula to convert the Fahrenheit temperature to Celsius:
Celsius = (5/9) * (Fahrenheit -32)
In order to convert the Fahrenheit temperature to Kelvin, you must first convert it to Celsius, and then add 273. Hint: Use the getCelsius() method inside of the getKelvin() method!
Demonstrate the Temperature class by writing a separate program that asks the user for a Fahrenheit temperature. The program should create an instance of the Temperature class, with the value entered by the user passed to the constructor. The program should then call the object’s methods to display the temperature in Celsius and Kelvin.
Answer: Hey dear student finds the solution of your query, if you have any doubt feel free to ask. Thanks!!
Copy to code: This code has Tempreature class and a double variable,constructor,setter and getters.In main, create object of the Temperature class and call all methods of the class,print both tempreatures.
import java.io.*;
class Temperature //Temperature class
{
double ftemp; //data member of the class
public Temperature(double tempF) //constructor
{
ftemp = tempF;
}
public void setFahrenheit(double f) //method to set
setFahrenheit
{
ftemp = f;
}
public double getFahrenheit() //method to return value
from ftemp
{
return ftemp;
}
public double getCelsius() //method to return value as
Celsius
{
double celsius;
celsius =(ftemp-32) ;
celsius = celsius*0.555;
return celsius;
}
public double getKelvin() //method to return value in
Kelvin
{
double kelvin;
kelvin = getCelsius(); //call
getCelsius()
kelvin = kelvin+273;
return kelvin;
}
}
class Main
{
public static void main(String[]args)
{
double c,k;
Temperature t = new
Temperature(68.52);//create object of the Temperature class
t.setFahrenheit(78.2);//call
setFahrenheit()
c = t.getCelsius();//call
getCelsius()
k = t.getKelvin();//cll
getKelvin()
System.out.println("Temperature in
Celcius: "+c);//print both Temperatures
System.out.println("Temperature in
Kelvin: "+k);
}
}
Screenshots of the code:
Snapshot ofthe output: