Having Trouble with Setters and Getter

Tell us what’s happening:
Describe your issue in detail here.

I have been working on this one for a while and I am trying to avoid looking at the solution like I tend to do. I am not sure how to make the distinction between Celsius and Fahrenheit when tracking the number. I know it has something to do with using both equations in the code but I’m not sure how to set it up. Any assistance would be great!

  **Your code so far**
// Only change code below this line
class Thermostat {
constructor(temperature){
  this._temperature = temperature;
}
get temperature(){
  return this._temperature;
}
set temperature(celsiusTemp){
  celsiusTemp = 5/9 * (this.temperature -32);
}
}
// Only change code above this line

const thermos = new Thermostat(76); // Setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in Celsius
thermos.temperature = 26;
temp = thermos.temperature; // 26 in Celsius
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36

Challenge: Use getters and setters to Control Access to an Object

Link to the challenge:

I am not sure how to make the distinction between Celsius and Fahrenheit when tracking the number.

Without looking at your code…

It’s kind of a weird little problem. (But then in real world coding, sometimes you get specifications that just don’t seem to make sense, but you still have to code them.)

You have two conflicting ideas here:

The constructor accepts a Fahrenheit temperature.

In the class, create a getter to obtain the temperature in Celsius and a setter to set the temperature in Celsius.

So, the constructor will deal in F and the getter and setter will deal in C. So, you either store the value in F and then the getter and setter will have to do conversions, or … you convert to C in the constructor and store it in C and then your getter and setter don’t have to convert. Either will work, but I think one of them will be a little less work.

Looking at your code …

It looks like you are storing the temp in F (since you do no conversion in your constructor). I see that your getter is just returning that (is that what you want?) and your setter:

set temperature(celsiusTemp){
  celsiusTemp = 5/9 * (this.temperature -32);
}

you’ve got a conversion there, but I think you have two issues. First, what is this.temperature? Is that your class property name? And secondly, I think you have the formula backwards - do you really want to store the value into celsiusTemp, the parameter you passed in?

See if that helps.

This absolutely helped! I ended up converting to C in the constructor and I was able to correct the setter. Thank you so much!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.