我正在尝试编写一个错误来移动附加到自定义 Room 对象的数组,同时记录每个图 block 被踩过的次数。
Room 对象工作正常,移动和计数也正常。但是,退出 nextMove
方法后,bug 的坐标 bugX
和 bugY
以某种方式恢复为 0
。它们的值仅在退出该方法时恢复;甚至 nextMove
方法本身的最后一行代码也使用它们的新值。
附上了该方法的相关部分,但可以根据要求添加其他部分。
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;
}
分配起始坐标的声明不在任何循环内,更不用说调用变量本身了。
最佳答案
这个问题是 @T.J.Crowder 在他的回答中描述的问题,尽管适用于 java。
在java中作为参数传递的变量是按值传递的。如果接收参数的方法更改了该值,则更改仅影响该方法内部的值。 “外部”值不会改变。
您可以做的是将坐标封装在一个对象中,并将封装对象作为参数传递。 然后该方法将按值接收对象,并更改其状态(而不是对象的值)。
要更深入地了解,请参阅 this question
编辑我:
我稍微清理了一下代码。虽然它缺少 room
和 simSentinel
的声明,但如果您添加,您应该有一个正在运行的示例。
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);
}
}
}
关于java - 为什么变量更改不会持久化方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52246358/