所以,在我的java类的开始,我定义了全局: static long world;
。 然后我有几个函数使用world
作为参数。其中一个名为setCell的函数无法按预期工作,我无法弄清楚原因。我曾尝试误差的println命令搜索,所以现在我的代码看起来是这样的:方法不全局更新变量?
public static long setCell(long world, int col, int row, boolean newval){
if(col>= 0 && col<8 && row>=0 && row<8){
int bitPosition = col + 8*row;
long newWorld = PackedLong.set(world, bitPosition, newval);
System.out.println(newWorld);
world = newWorld;
System.out.println(world);
return world;
}
else{
return world;
}
}
代码的主要思想是,它应该通过改变其位中的一个与PackedLong.set
方法更新world
(这是运行良好),然后返回新更新的world
。
如果我们现在运行:
world =0x20A0600000000000L;
System.out.println(world);
setCell(world, 1, 1, true);
System.out.println(world);
的主要方法
,我们得到以下的输出:
2350984558603665408 2350984558603665920 2350984558603665920 2350984558603665408
由此我得出的结论是命令里面的setCell
方法的工作原理打算,但该方法不会在整个代码中“全局”地更改world
。我该如何解决这个问题? 非常感谢! :)
这是正确的,但是如何解决问题? –
使用不隐藏全局变量的参数名称。 – Kelvin
@凯文谢谢你的回答!你能不能更具体一点我应该改变我的变量?我在开始时尝试写'static long initialWorld',在main方法的每个地方都把'world'改成'initialWorld',并且不改变'setCell'中的任何东西,但错误仍然存在。 – Jhonny