有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

私有Java setter不会更改整数的值

编辑:添加的MovementDataStorage数据=新的MovementDataStorage();以课堂评论中指出的主要问题加以澄清

我有三门课,都在同一个包里。 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的值不会增加-我尝试从main方法和goForward方法内部检查该值

如果我手动更改int locationNorth值,我可以看到更改。如果我通过move.goForward();来做,它似乎不会改变

如果在我的main方法中添加:

data.setLocationNorth(data.getLocationNorth()+1);

System.out.println(data.getLocationNorth());

int locationNorth的值确实成为我想要的值

代码运行和编译时没有错误/异常


共 (3) 个答案

  1. # 1 楼答案

    表情

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

    显然不是真的。我猜它不是初始化正确就是有不同的值

  2. # 2 楼答案

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

    一种解决方案是使用来自ActionsMovementMovementDataStorage

    class Main {
        ActionsMovement move = new ActionsMovement();
        move.goForward();
        System.out.println(move.getData().getLocationNorth());
    }
    
    class ActionsMovement {
    
        public MovementDataStorage getData() {
            return this.data;
        }
    }
    

    如果您主要需要MovementDataStorage,您可以创建一个实例并将其作为参数发送

    class Main {
        MovementDataStorage data = new MovementDataStorage();
        ActionsMovement move = new ActionsMovement(data);
    
        move.goForward();
        System.out.println(move.getData().getLocationNorth());
    }
    
    class ActionsMovement {
    
        MovementDataStorage data;
    
        public ActionsMovement(MovementDataStorage data) {
            this.data = data;
        }
    
        public ActionsMovement() {
            this.data = new MovementDataStorage();
        }
    
        public MovementDataStorage getData() {
            return this.data;
        }
    }
    
  3. # 3 楼答案

    因此,您的ActionsMovement已经包含一个MovementDataStorage,因此不需要在主方法中重新创建该对象

    因此,在ActionsMovement类中,您可能应该有一个函数来检索MovementDataStorage,如下所示:

    public getMovementDataStorage() {
        return this.data;
    }
    

    然后从你的主要目标开始,你可以这样做:

    ActionsMovement move = new ActionsMovement();
    
    move.goForward();
    System.out.println(data.getMovementDataStorage().getLocationNorth());