Write a Java class to represent a temperature The class has
Solution
TemperatureTester.java
import java.util.Scanner;
public class TemperatureTester {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print(\"Please enter the initial temperature: \");
double tempC = scan.nextDouble();
TemperatureC temp = new TemperatureC(tempC);
System.out.println(\"The current temperature in Celsius is: \"+temp.getC());
System.out.println(\"The current temperature in Fahrenheit is: \"+temp.getF());
System.out.println(\"The current temperature in Kelvin is: \"+temp.getK());
System.out.print(\"Please enter a new temperature: \");
double newTempC = scan.nextDouble();
temp.setC(newTempC);
System.out.println(\"The current temperature in Celsius is: \"+temp.getC());
System.out.println(\"The current temperature in Fahrenheit is: \"+temp.getF());
System.out.println(\"The current temperature in Kelvin is: \"+temp.getK());
}
}
TemperatureC.java
public class TemperatureC {
private double temperatureC;
public TemperatureC(double temperatureC){
this.temperatureC = temperatureC;
}
public void setC(double temperatureC){
if(temperatureC > 273.15){
this.temperatureC = temperatureC;
}
else{
this.temperatureC=0;
}
}
public double getC(){
return temperatureC;
}
public double getF(){
return temperatureC*1.8 + 32;
}
public double getK(){
return temperatureC+273.15;
}
}
Output:
Please enter the initial temperature: 20
The current temperature in Celsius is: 20.0
The current temperature in Fahrenheit is: 68.0
The current temperature in Kelvin is: 293.15
Please enter a new temperature: 4000
The current temperature in Celsius is: 4000.0
The current temperature in Fahrenheit is: 7232.0
The current temperature in Kelvin is: 4273.15

