toString和booleans

时间:2016-02-08 15:38:24

标签: java string boolean tostring

我正在制作一个灯泡类,我必须让它处于开/关状态,无论它是否烧坏,以及它的颜色。无论出于何种原因,我都能得到正确的切换但是,我的toString打印出错误的答案,我无法弄清楚原因。我不习惯使用布尔值,所以我的代码可能不支持我的逻辑。有人可以帮忙吗?

以下是代码:

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;
 }

这是一个测试,项目允许我运行以显示我的结果:

> run Light

1。测试灯() * PASS:on设置正确(true) PASS:正确设置了burntOut(false) PASS:颜色设置正确(白色) * 失败:toString无法按预期工作(白色烧毁)

  1. 测试灯(布尔值b,布尔值o,字符串c) * PASS:on设置正确(false) PASS:正确设置了burntOut(true) PASS:颜色设置正确(绿色) * 失败:toString无法按预期工作(绿色烧毁)

1 个答案:

答案 0 :(得分:0)

此:

if(on = true){

您不是比较,而是分配值。要进行比较,请使用==

if(on == true){

或者,甚至更简单:

if(on){

(注意:您的代码中有几个地方有这个错误。这只是说明其中一个。也相应地修复其他地方。)