【发布时间】:2020-02-10 11:24:20
【问题描述】:
编辑:添加了 MovementDataStorage 数据 = new MovementDataStorage();到 cmets 中指出的主类进行澄清。
我有 3 个类,都在同一个包中。 Main 类中 main 方法的代码 sn-p:
ActionsMovement move = new ActionsMovement();
MovementDataStorage data = new MovementDataStorage();
move.goForward();
System.out.println(data.getLocationNorth()); //this would show 0, intended result is 1
我的 ActionsMovement 类具有以下 sn-p:
MovementDataStorage data = new MovementDataStorage();
public void goForward()
{
if (data.getDirection().equals("North")) {
data.setLocationNorth(data.getLocationNorth() + 1);
}
}
最后,我的 MovementDataStorage 有以下代码 sn-p:
private int locationNorth;
private String direction = "North";
public int getLocationNorth() {
return locationNorth;
}
public void setLocationNorth(int locationNorth) {
this.locationNorth = locationNorth;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
当 move.goForward(); 运行时,int locationNorth 的值不会增加 - 我尝试从 main 方法和 goForward 方法内部检查值。
如果我手动更改int locationNorth 值,我可以看到更改。如果我通过move.goForward(); 进行操作,它似乎不会改变。
如果在我的main 方法中添加:
data.setLocationNorth(data.getLocationNorth()+1);
System.out.println(data.getLocationNorth());
int locationNorth 的值确实变成了我想要的值。
代码运行和编译没有错误/异常
【问题讨论】:
-
这是调试器派上用场的地方...
-
简短建议:locationNorth 未在您的班级中初始化。
-
@Andrea 这就是它以默认值 0 开头的原因
-
@Kleronomas 的值可能不等于“North”
标签: java private getter setter