I am making a class for a lightbulb and I have to have it be on/off state whether it's burntout or not, and its color. For whatever reason I get the right things to switch but, my toString prints the wrong answer and I cannot figure out why. I am not used to working with booleans and so my code may not support my logic. Can someone help?
Here is the code:
public class Light
{
// Variables that will be initialized in the Light constructors.
private boolean on;
private boolean burntOut;
private String color = "";
// Default constructor that sets the bulb to on, not burnt out, and "white".
public Light()
{
on= true;
burntOut = false;
color = "white";
}
// This constructor sets the variable "on" to the parameter o. The burntOut
// variable is set to the parameter b. If burntOut
// is true, on is set to false, no matter what value is stored in o.
// The color variable is set to the parameter c only if c is "red", "green"
// or "blue". The constructor ignores the case of the value in c. If c holds
// any value other than "red", "green" or "blue", the constructor sets
// color to "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";
}
}
// The toString method returns a String with the Light in the format:
// off red burnt out
// on green not burnt out
//
// Notice there is one space between "off"/"on" and the value for color,
// and a tab before the "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 is a test the project is allowing me to run to show my results:
> run Light
1. Test Light() * PASS: on is set correctly (true) PASS: burntOut is set correctly (false) PASS: color is set correctly (white) * FAIL: toString does not work as expected (on white burnt out)
- Test Light(boolean b, boolean o, String c) * PASS: on is set correctly (false) PASS: burntOut is set correctly (true) PASS: color is set correctly (green) * FAIL: toString does not work as expected (on green burnt out)