java - toString and booleans -
this question has answer here:
- how use boolean in if statement? 8 answers
i making class lightbulb , have have on/off state whether it's burntout or not, , color. whatever reason right things switch but, tostring prints wrong answer , cannot figure out why. not used working booleans , code may not support logic. can help?
here code:
public class light { // variables initialized in light constructors. private boolean on; private boolean burntout; private string color = ""; // default constructor sets bulb on, not burnt out, , "white". public light() { on= true; burntout = false; color = "white"; } // constructor sets variable "on" parameter o. burntout // variable set parameter b. if burntout // true, on set false, no matter value stored in o. // color variable set parameter c if c "red", "green" // or "blue". constructor ignores case of value in c. if c holds // value other "red", "green" or "blue", constructor sets // color "white". public light(boolean o, boolean b, string c) { on = o; burntout=b; if(burntout=true){ on = false; } else{ on= o; } if(c.equalsignorecase("red")){ color = "red"; } if(c.equalsignorecase("blue")){ color = "blue"; } if (c.equalsignorecase("green")){ color="green"; } else { color = "white"; } } // tostring method returns string light in format: // off red burnt out // on green not burnt out // // notice there 1 space between "off"/"on" , value color, // , tab before "burnt out" or "not burnt out". public string tostring() { string x =""; if(on = true){ x+="on" + " "; } if(on = false){ x+= "off" + " "; } x+= color; if (burntout = false){ x+="\t" + "not burnt out"; } if(burntout = true){ x+= "\t" + "burnt out"; } return x; }
and here test project allowing me run show results:
> run light
1. test light() * pass: on set correctly (true) pass: burntout set correctly (false) pass: color set correctly (white) * fail: tostring not work expected (on white burnt out)
- test light(boolean b, boolean o, string c) * pass: on set correctly (false) pass: burntout set correctly (true) pass: color set correctly (green) * fail: tostring not work expected (on green burnt out)
this:
if(on = true){
you're not comparing, you're assigning value. compare, use ==
:
if(on == true){
or, simpler:
if(on){
(note: there several places in code have error. illustrating 1 of them. fix others accordingly well.)
Comments
Post a Comment