Java setter不会更改整数的值

问题描述 投票:1回答:1

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的值的确变成了我想要的。

代码运行并编译,没有错误/异常

java private getter setter
1个回答
0
投票

表达式

if (data.getDirection().equals("North"))

显然没有评估为真。我的猜测是它要么未正确初始化,要么具有不同的值。


0
投票

问题是您有两个MovementDataStorage,一个在Main类中打印,另一个在ActionsMovement类中设置其值。

© www.soinside.com 2019 - 2024. All rights reserved.