我正在制作战舰游戏 我有 3 个类(class)和一名司机。
在玩家类别中
我有这个方法
public void hitownshiporGrenade(String[][] grid, String attack) {
// checking if attack hits our ship, appropriate
// if it does place an s in the array
if (attack.equals(s1)) {
// -97 gives us a starting point at 0 for 'a' to
// store in array, same for 49 and '1'
grid[attack.charAt(0) - 97][attack.charAt(1) - 49] = "s ";
System.out.println("ship hit!");
s1Sunk = true;
}
我有声明的变量和顶部的 setter/getter
private boolean s1Sunk;
public boolean isS1Sunk() {
return s1Sunk;
}
现在在我的另一个类(class)
Player player = new Player();
System.out.println(player.isS1Sunk());
如果我在驱动程序中的方法中调用它,那么无论第一个方法条件使其为真,它都会保持错误;
最佳答案
假设您在代码示例中提到的方法都属于同一个 Player
类定义,然后通过以下操作创建 Player
的新类实例(对象)
Player player = new Player();
您创建一个新的、独立的(与所有其他)Player
类的实例。除非您为该特定对象运行 hitownshiporGrenade
,否则它的变量不会改变。
考虑以下因素:
Player player1 = new Player(); //player1.isSunk is false
Player player2 = new Player(); //player2.isS1Sunk is again false,
//and separate from player1.isS1Sunk
player1.hitownshiporGrenade(foo, bar) //This changes player1.isSunk to true
System.out.print(player1.getIsSunk()); //true, assuming lucky hits
System.out.print(player2.getIsSunk()); //false
我还建议您阅读如何使用正确的 Camel case when naming your variables !它将使您的代码更易于阅读,并在您阅读代码时减轻您的麻烦。
关于java - 在类之间传递 boolean 值未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52377093/