2016-02-08 20 views
-2

我正在为一个灯泡制作班级,我必须让它处于开/关状态,不管是否烧坏,以及它的颜色。无论出于何种原因,我都能切换正确的东西,但是,我的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:设置颜色正确地(白色) * FAIL:如预期的toString不起作用(在白色烧坏)

  • 测试灯(布尔B,布尔O,串c) * PASS :上设置正确(假) PASS:burntOut正确(真)设置 PASS:颜色设置正确(绿色) *失败:的toString不能按预期工作(绿色烧坏)
  • +0

    '='用于分配一个值。 – Satya

    +0

    '==',而不是'='。或者,更好的是,如果(上){...}其他{...}'。 –

    +0

    那么有道理 –

    回答

    0

    此:

    if(on = true){ 
    

    你不比较,你分配值。为了比较,使用==

    if(on == true){ 
    

    甚至更​​简单:

    if(on){ 
    

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

    +0

    这是正确的。 +1。 – Krishna

    +0

    这非常有道理谢谢你提醒这样一个简单的规则! –

    +0

    @BobD:当你前进时可能会有帮助的一件事就是考虑你的变量的语义名称。例如,如果将变量'on'称为'isOn',那么代码可能类似于:'if(this.isOn)',它在语义上非常清楚地读作“如果这是打开的”。 – David