2016-02-08 66 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