Skip to content

Instantly share code, notes, and snippets.

@jacobtender
Created April 10, 2019 00:56
Show Gist options
  • Save jacobtender/43897d6d1429a42c1db2ca214c2c4cd4 to your computer and use it in GitHub Desktop.
Save jacobtender/43897d6d1429a42c1db2ca214c2c4cd4 to your computer and use it in GitHub Desktop.
Solved Source for: Temperature
/*
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:
• ftemp: a double that holds a Fahrenheit temperature.
The class should have the following methods:
• Constructor: The constructor accepts a Fahrenheit temperature (as a double) and stores it in the ftemp field.
• setFahrenheit: The set Fahrenheit method accepts a Fahrenheit temperature (as a double) and stores it in the ftemp field.
• getFahrenheit: Returns the value of the ftemp field as a Fahrenheit temperature (no conversion required)
• getCelsius: Returns the value of the ftemp field converted to Celsius. Use the following formula to convert to Celsius:
Celsius = (5/9) * (Fahrenheit - 32)
• getKelvin: Returns the value of the ftemp field converted to Kelvin. Use the following formula to convert to Kelvin:
Kelvin = ((5/9) * (Fahrenheit - 32)) + 273
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 the following format (for example,
if the temperature in Fahrenheit was -40):
The temperature in Fahrenheit is -40.0
The temperature in Celsius is -40.0
The temperature in Kelvin is 233.0
*/
import java.util.Scanner;
public class Temperature
{
double ftemp;
Temperature(double ftemp)
{
this.ftemp = ftemp;
}
public void setFahrenheit(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);
}
public static void main(String[] args) {
double ftemp; // Holds temp in Fahrenheit
Scanner input = new Scanner(System.in);
System.out.print("Enter a Fahrenheit temperature:");
ftemp = input.nextDouble();
Temperature temp = new Temperature(ftemp);
temp.setFahrenheit(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());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment