java - 我的代码中的逻辑错误

标签 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!");
 }

 }

}

最佳答案

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

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

this.speed = SLOW;

它是一个 int,因此无需在此处将常量转换为 String。您可以相应地更改其他赋值语句,并且还可以返回 this.speed

关于java - 我的代码中的逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27070191/

相关文章:

c# - 将存储在对象 >= 中的数值与另一个对象进行比较

Java JNA 从 D2D1 映射 D2D1CreateFactory

java - 按下回车键时执行登录按钮

Java 对象数组(每个对象具有超过 1 个元素) 如何更改特定对象中的 1 个元素

c++ - CIS115 GradeBook 应用程序不添加成绩

javascript - 如何通过对象名称动态检索对象属性?

Javascript 对象 : iterating over properties

java - JInternalFrame - 删除左上角的下拉按钮

java - 提交表单时收到错误消息 : "The request sent by the client was syntactically incorrect"

java - Android 应用小部件 onUpdate()