我正在爲一個燈泡製作班級,我必須讓它處於開/關狀態,不管是否燒壞,以及它的顏色。無論出於何種原因,我都能切換正確的東西,但是,我的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不能按預期工作(綠色燒壞)
'='用於分配一個值。 – Satya
'==',而不是'='。或者,更好的是,如果(上){...}其他{...}'。 –
那麼有道理 –