我是java的新手,所以我有一个初学者的问题。 我有一个关于编写灯泡程序的工作,在其中我必须关闭和打开它。 RGBColor类(您将在代码中看到它的某些引用)是LightBulb类所基于的另一个类。这是我到目前为止在LightBulb课上所做的代码:
public class LightBulb
{
private RGBColor _color;
private boolean _switchedOn;
private final int MIN_VAL = 0;
private final int MAX_VAL = 255;
public LightBulb(int red, int green, int blue)
{
_color = new RGBColor(red, green, blue);
_switchedOn = false;
if((red < MIN_VAL) || (red > MAX_VAL) || (green < MIN_VAL) || (green > MAX_VAL) || (blue < MIN_VAL) || (blue > MAX_VAL))
{
red = MIN_VAL;
green = MIN_VAL;
blue = MIN_VAL;
}
}
public LightBulb(RGBColor color)
{
_color = new RGBColor(color);
_switchedOn = false;
}
public LightBulb(LightBulb other)
{
_color = new RGBColor(other._color);
_switchedOn = false;
}
public String toString()
{
String onOrOff;
if(isSwitchedOn() == true)
onOrOff = "On";
else
onOrOff = "Off";
return ("(" + _color.getRed() + "," + _color.getGreen() + "," + _color.getBlue() + ")" + ", " + onOrOff);
}
public RGBColor getColor()
{
return new RGBColor(_color);
}
public void setColor(RGBColor color)
{
_color = new RGBColor(color);
}
public boolean isSwitchedOn()
{
if((_color.getRed() == 0) && (_color.getGreen() == 0) && (_color.getBlue() == 0))
_switchedOn = false;
else
_switchedOn = true;
return _switchedOn;
}
public void switchLight()
{
//_switchedOn = !_switchedOn; // option 1: Doesn't switch it to the reversed value
if(isSwitchedOn() == true)
_switchedOn = false;
else
_switchedOn = true; // option 2: Doesn't switch it to the reversed value either
}
&#13;
当我构建LightBulb对象并尝试实现switchLight()方法时,我没有收到反转值...我很乐意知道你是否有提示对我来说如何才能收到它。
谢谢!
答案 0 :(得分:1)
看来你的逻辑与开关灯的含义是混合的。在switchLight()方法中,您正确设置_switchedOn布尔值,但是在isSwitchedOn()方法中,您没有询问_switchedOn布尔值,您正在检查颜色,然后根据颜色更改_switchedOn布尔值。我会说在这种方法中检查颜色是错误的,因为如果你将颜色设置为0表示它已关闭,你没有在任何地方做,你就不会保持原来的颜色。我会改变以下方法。
public boolean isSwitchedOn()
{
return _switchedOn;
}
public void switchLight()
{
_switchedOn = !_switchedOn; // This should work now.
}
另外,我会检查你的(r,g,b)构造函数。如果红色不在范围内会发生什么,但绿色和蓝色是什么?这是你想要的吗?