Home Ask Login Register

Developers Planet

Your answer is one click away!

Bob D February 2016

toString and booleans

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;
    on = false;
    on= o;
    color = "red"; 
    color = "blue";
  if (c.equalsIgnoreCase("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 ou        


David February 2016


if(on = true){

You're not comparing, you're assigning the value. To compare, use ==:

if(on == true){

Or, even simpler:


(Note: There are several places in your code which have this error. This is illustrating only one of them. Fix the others accordingly as well.)

Post Status

Asked in February 2016
Viewed 3,888 times
Voted 14
Answered 1 times


Leave an answer

Quote of the day: live life