我的代碼中似乎有一個邏輯錯誤。這是因爲我的第一個風扇對象(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!");
}
}
}
是Daniel Liang介紹Java教科書的作業。我意識到這個問題已經使用他的書教了很多年! – hfontanez 2014-11-21 20:58:34