我的代码中似乎存在逻辑错误。这是因为我的第一个扇形对象 (FanOne) 应显示以下输出:速度:2,半径:10.0,颜色:黄色。
相反,它显示速度:1
我认为我的 setSpeed() 方法有问题..但对我来说,似乎一切都应该按预期进行。请指教,谢谢。
public class TestFan {
public static void main(String[] args) {
Fan FanOne = new Fan();
FanOne.fanOn();
FanOne.setColor("yellow");
FanOne.setCustomSpeed("MEDIUM");
FanOne.setCustomRadius(10);
System.out.println(FanOne.toString());
System.out.println();
Fan FanTwo = new Fan();
FanTwo.fanOff();
FanTwo.setCustomRadius(5);
FanTwo.setColor("blue");
System.out.println(FanTwo.toString());
}
}
public class Fan {
// Declare constant data fields
final int SLOW = 1;
final int MEDIUM = 2;
final int FAST = 3;
private int speed;
private boolean on;
private double radius;
private String color;
// Construct a default fan
public Fan() {
speed = SLOW;
on = false;
radius = 5;
color = new String("Blue");
}
// Set fan off
public boolean fanOff() {
on = false;
return on;
}
// Set fan on
public boolean fanOn() {
on = true;
return on;
}
public double getRadius() {
return radius;
}
// Set custom radius
public void setCustomRadius(double rad) {
radius = rad;
}
public int getSpeed() {
return speed;
}
// Set custom speed
public String setCustomSpeed(String speed) {
if (speed.equals("SLOW")) {
this.speed = SLOW;
} else if (speed.equals("MEDIUM")) {
this.speed = MEDIUM;
} else if (speed.equals("FAST")) {
this.speed = FAST;
}
return speed;
}
public String getColor() {
return color;
}
public void setColor(String colorName) {
color = colorName;
}
public String toString() {
if (on == true) {
return ("Speed: " + speed + ", " + "Radius: " + radius + ", " + "Color: " + color);
} else {
return ("Color: " + color + ", " + "Radius: " + radius + ", Alert: " + "The fan is off!");
}
}
}
最佳答案
在 speed
、setCustomSpeed
的 setter 方法中,您仅更改本地 String
变量 speed
,不是实例变量speed
。它保持在 SLOW
或 1
不变。
使用 this
来限定您所指的实例变量,例如
this.speed = SLOW;
它是一个 int
,因此无需在此处将常量转换为 String
。您可以相应地更改其他赋值语句,并且还可以返回 this.speed
。
关于java - 我的代码中的逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27070191/