首页 > 解决方案 > 为什么变量更改不持久化方法调用?

问题描述

我正在尝试编写一个错误来移动附加到自定义 Room 对象的数组,同时计算每个瓷砖被踩了多少次。

Room 对象工作正常,移动和计数也是如此。但是,在退出该方法后,错误的坐标bugXbugY会以某种方式恢复。它们的值仅在退出方法时恢复;甚至方法本身的最后一行代码也使用了它们的新值。0nextMovenextMove

该方法的相关部分已附上,但可以根据要求添加其他部分。

if (dirNum == 0 && bugY < length-1)         //Move up
    bugY++;
else if (dirNum == 1 && bugX < width-1)     //Move right
    bugX++;
else if (dirNum == 2 && bugY > 0)           //Move down
    bugY--;
else if (dirNum == 3 && bugX > 0)           //Move left
    bugX--;
else {
    System.out.println("Error: Cannot move " + direction + ".");
    canMove = false;
    dirNum = generator.nextInt(4);
    continue;
}

这是命令本身的上下文。

while (endSim == false) {
    nextMove(bugX, bugY);
    System.out.print(room.printRoom() + "\n\nNext move? (y/n) ");
    simSentinel = in.next();
    if (simSentinel.charAt(0) == 'n')
        endSim = true;
}

分配起始坐标的声明不在任何循环内,更不用说调用变量本身的地方了。

标签: javavariables

解决方案


问题是@TJCrowder 在他的回答中描述的问题,虽然适用于java。

在java中作为参数传递的变量是按值传递的。如果值被接收参数的方法更改,则更改仅影响该方法内部的值。“外部”值不会改变。

您可以做的是将坐标封装在一个对象中,并将封装对象作为参数传递。然后该方法将按值接收对象,并更改其状态(而不是对象的值)。

如需更深入的了解,请参阅此问题

编辑我:

我稍微清理了代码。虽然它缺少 and 的声明roomsimSentinel但如果您添加,您应该有一个运行示例。

public class Bug{
    public int x=0;
    public int y=0; 
}

    public class SimpleSim {

    private int  dirNum = 0;
    private int length = 20;
    private int width = 20;
    private boolean canMove = true;
    private Random generator = new Random();
    private boolean endSim = false;

    public static void main(String [] args) {
        SimpleSim simpleSim = new SimpleSim();
        simpleSim.start();

    }

    private void start() {
        Bug myBug = new Bug();
        // Give the bug some initial x, y values.
        myBug.x = 0;
        myBug.y = 0;

        while (endSim == false) {
            nextMove(myBug);
            System.out.print(room.printRoom() + "\n\nNext move? (y/n) ");
            simSentinel = in.next();
            if (simSentinel.charAt(0) == 'n')
               endSim = true;
            }

        }
    }

    public void nextMove(Bug bug){
        if (dirNum == 0 && bug.y < length-1)         //Move up
           bug.y++;
        else if (dirNum == 1 && bug.x < width-1)     //Move right
           bug.x++;
        else if (dirNum == 2 && bug.y > 0)           //Move down
           bug.y--;
        else if (dirNum == 3 && bug.x > 0)           //Move left
           bug.x--;
        else {
           System.out.println("Error: Cannot move " + "?" + ".");
           canMove = false;
           dirNum = generator.nextInt(4);
        }

     }

}

推荐阅读