java - 为什么变量更改不持久化方法调用?
问题描述
我正在尝试编写一个错误来移动附加到自定义 Room 对象的数组,同时计算每个瓷砖被踩了多少次。
Room 对象工作正常,移动和计数也是如此。但是,在退出该方法后,错误的坐标bugX
和bugY
会以某种方式恢复。它们的值仅在退出方法时恢复;甚至方法本身的最后一行代码也使用了它们的新值。0
nextMove
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;
}
分配起始坐标的声明不在任何循环内,更不用说调用变量本身的地方了。
解决方案
问题是@TJCrowder 在他的回答中描述的问题,虽然适用于java。
在java中作为参数传递的变量是按值传递的。如果值被接收参数的方法更改,则更改仅影响该方法内部的值。“外部”值不会改变。
您可以做的是将坐标封装在一个对象中,并将封装对象作为参数传递。然后该方法将按值接收对象,并更改其状态(而不是对象的值)。
如需更深入的了解,请参阅此问题
编辑我:
我稍微清理了代码。虽然它缺少 and 的声明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);
}
}
}
推荐阅读
- visual-studio - 在 Visual Studio 中更新 Nuget 包后构建定义未构建
- javascript - 如何从数组中提取对象?
- javascript - JavaScript 表格在加载/刷新时闪烁。想知道我怎样才能避免这种情况发生?
- r - 如何在r中的nnfor包中获得mlp层神经元的权重?
- ruby-on-rails - 为什么 Heroku 上的 secret_key_base 为空白(Rails 5.2)
- linux - 使用脚本外壳获取文件中每行的最后两个字母
- notepad++ - 在记事本++中用正则表达式替换左侧文本
- .net-core - 是否有任何分析 api 可用于以 clr 版本托管的应用程序,因为 IIS 中没有托管代码
- kubernetes - 如何将运行状况检查放入部署清单中?
- python - 如何从类中的回调方法正确调用方法?