我的代码中的逻辑错误

时间:2014-11-21 20:55:13

标签: java object

我的代码中似乎有一个逻辑错误。这是因为我的第一个扇形对象(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!");
 }

 }

}

2 个答案:

答案 0 :(得分:2)

speedsetCustomSpeed的setter方法中,您只更改了本地String变量speed,而不是实例变量speed。它在SLOW1保持不变。

使用this来限定您的实例变量,例如

this.speed = SLOW;

它是int所以不需要在此处将常量转换为String。您可以相应地更改其他赋值语句,也可以返回this.speed

答案 1 :(得分:2)

您的问题称为阴影。你的代码在这里:

// Set custom speed
 public int setCustomSpeed(String speed) {
  if (speed.equals("SLOW")) {
   speed = String.valueOf(SLOW);  
 } else if (speed.equals("MEDIUM")) {
   speed = String.valueOf(MEDIUM); 
 } else if (speed.equals("FAST")) {
   speed = String.valueOf(FAST);
 }
return speed;
}

将局部变量速度设置为2,使Fan类变量速度等于之前的值(构造函数将其设置为1)。因此,我们需要使用this.speed来区分对象的速度变量。这表明要使用哪个变量。

// Set custom speed
 public String setCustomSpeed(String speed) {
  if (speed.equals("SLOW")) {
   this.speed = String.valueOf(SLOW);  
 } else if (speed.equals("MEDIUM")) {
   this.speed = String.valueOf(MEDIUM); 
 } else if (speed.equals("FAST")) {
   this.speed = String.valueOf(FAST);
 }
return this.speed;
}

为避免将来出现这种情况,您应该考虑使用不同命名的变量,并阅读并理解变量范围和阴影。

相关问题