EDIT:添加了MovementDataStorage数据=新的MovementDataStorage();注释中指出的要澄清的主要类别。
我有3个班级,都在同一个包中。Main类中main方法的代码片段:
ActionsMovement move = new ActionsMovement();
MovementDataStorage data = new MovementDataStorage();
move.goForward();
System.out.println(data.getLocationNorth()); //this would show 0, intended result is 1
我的ActionsMovement类具有以下片段:
MovementDataStorage data = new MovementDataStorage();
public void goForward()
{
if (data.getDirection().equals("North")) {
data.setLocationNorth(data.getLocationNorth() + 1);
}
}
最后,我的MovementDataStorage具有以下代码段:
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
的值不会增加-我尝试从主方法和goForward
方法内部检查值。
如果手动更改int locationNorth
值,则可以看到更改。如果我通过move.goForward();
进行操作,它似乎没有改变。
如果在我的main
方法中添加:
data.setLocationNorth(data.getLocationNorth()+1);
System.out.println(data.getLocationNorth());
int locationNorth
的值的确变成了我想要的。
代码运行并编译,没有错误/异常
表达式
if (data.getDirection().equals("North"))
显然没有评估为真。我的猜测是它要么未正确初始化,要么具有不同的值。
问题是您有两个MovementDataStorage
,一个在Main
类中打印,另一个在ActionsMovement
类中设置其值。