I have a task with a temperature converter program. I have to use one veriable in a class what is used by two setter and two getter method.
This is the main class:
public class Main {
public static void main(String[] args) {
Homero ho = new Homero();
ho.setCelsius(0);
System.out.println(ho.getFahrenheit());
System.out.println(ho.getCelsius());
ho.setFahrenheit(212);
System.out.println(ho.getFahrenheit());
System.out.println(ho.getCelsius());
}
}
How can I say to the getters that when the main function set the first setter, the getter return with this... and in the second time return with that...
This is the Homero class:
public class Homero {
double celsius;
public void setCelsius(double celsius){
this.celsius = celsius;
}
public void setFahrenheit(double fahr){
this.celsius = fahr;
}
public double getFahrenheit(){
return (this.celsius*9)/5+32;
}
public double getCelsius(){
return (this.celsius-32)*5/9;
}
}
And this would be the proper output:
And the wrong output what I've got.
The getter and setter for celsius does not need a conversion. Do your calculations in the getter and setter for fahrenheit:
public void setCelsius(double celsius){
this.celsius = celsius;
}
public void setFahrenheit(double fahr){
this.celsius = (fahr -32)*5/9;
}
public double getFahrenheit(){
return this.celsius*9/5+32;
}
public double getCelsius(){
return this.celsius;
}