在类之间传递布尔值不按预期工作

问题描述 投票:0回答:1

我正在制作战舰游戏,我有3个班级和一个司机。

在玩家类中

我有这种方法

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;
    }

我有声明的变量和顶部的getter

private boolean s1Sunk; 
public boolean isS1Sunk() {
    return s1Sunk;
}

现在在我的另一堂课

Player player = new Player();
System.out.println(player.isS1Sunk());

如果我在驱动程序中的一个方法中调用它,那么即使第一个方法条件使其成立,它仍然是错误的。

java class boolean
1个回答
1
投票

假设您在代码示例中提到的方法都属于相同的Player类定义,那么通过执行创建Player的新类实例(对象)

Player player = new Player();

你创建一个新的,独立的(来自所有其他)Player类的实例。除非你为该SPECIFIC对象运行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!它将使您的代码更容易阅读,并在您完成它时为您节省很多麻烦。

© www.soinside.com 2019 - 2024. All rights reserved.