【问题标题】:Why am I getting null as a value of array? [duplicate]为什么我得到 null 作为数组的值? [复制]
【发布时间】:2013-11-02 14:17:29
【问题描述】:

我有一个类 Hra1,它定义了游戏规则 (game=hra)。问题是,我得到一个空值,例如poleMinci==null,尽管在构造函数中创建了数组poleMinci。也就是说,玩家的 move 方法总是返回 false。

构造函数:

public Hra1()
{
    Mince [] poleMinci = new Mince[20];
    poleMinci[0] = new Mince("stříbrná", "coin.png");
    poleMinci[3] = new Mince("stříbrná", "coin.png");
    poleMinci[4] = new Mince("zlatá", "coin_gold.png");
    poleMinci[8] = new Mince("stříbrná", "coin.png");
    poleMinci[10] = new Mince("stříbrná", "coin.png");
    poleMinci[12] = new Mince("stříbrná", "coin.png");
}

玩家的移动方式:

public boolean tahHrace(Tah tah){
    if (poleMinci != null){
        int odkud = tah.getZPozice();
        int kam = tah.getNaPozici();
        boolean kamPrazdne;
        if (poleMinci [kam] != null) 
            kamPrazdne = false;
            else 
            kamPrazdne = true;

        if (kam > odkud && poleMinci [odkud] != null && kamPrazdne == true){
            poleMinci [kam] = poleMinci [odkud];
            poleMinci [odkud] = null;
            System.out.println("hráč táhl z pozice "+tah.getZPozice()
            + " na pozici "+tah.getNaPozici());
            return true;
        }
        else
             return false;

    }
    else
    return false;
}

【问题讨论】:

  • 这是你声明的局部变量和对象。
  • 用您的母语找到帖子很有趣:D

标签: java arrays null


【解决方案1】:

你正在隐藏一个变量:

public Hra1()
{
    // the following variable's *scope* is inside of this constructor only
    // outside of the constructor, the local variable below doesn't exist.
    Mince [] poleMinci = new Mince[20]; 

    poleMinci[0] = new Mince("stříbrná", "coin.png");
    poleMinci[3] = new Mince("stříbrná", "coin.png");
    poleMinci[4] = new Mince("zlatá", "coin_gold.png");
    poleMinci[8] = new Mince("stříbrná", "coin.png");
    poleMinci[10] = new Mince("stříbrná", "coin.png");
    poleMinci[12] = new Mince("stříbrná", "coin.png");
}

在那个构造函数中,因为poleMinci是在构造函数内部声明的,所以它只在构造函数内部可见。如果您在类中有一个同名的变量,它将为空。要解决此问题,请不要在本地重新声明变量。做:

public Hra1()
{

    // Mince [] poleMinci = new Mince[20]; // **** not this ****
    poleMinci = new Mince[20]; // **** but this. note the difference? ****

    poleMinci[0] = new Mince("stříbrná", "coin.png");
    poleMinci[3] = new Mince("stříbrná", "coin.png");
    poleMinci[4] = new Mince("zlatá", "coin_gold.png");
    poleMinci[8] = new Mince("stříbrná", "coin.png");
    poleMinci[10] = new Mince("stříbrná", "coin.png");
    poleMinci[12] = new Mince("stříbrná", "coin.png");
}

有关此问题的更多信息,请查看Variable Shadowing。大多数 IDE 要么会警告您可能正在执行此操作,要么具有允许他们执行此操作的设置。我使用 Eclipse 并设置了我的 IDE 来警告我。您可能也希望这样做。

【讨论】:

  • @BořekVavřík:不客气。有关此问题的更多信息,请查看Variable Shadowing。大多数 IDE 要么会警告您可能正在执行此操作,要么具有允许他们执行此操作的设置。我使用 Eclipse 并设置了我的 IDE 来警告我。您可能也希望这样做。
猜你喜欢
  • 2015-12-13
  • 2015-07-16
  • 1970-01-01
  • 2016-06-24
  • 2020-05-02
  • 1970-01-01
  • 2019-11-11
  • 1970-01-01
相关资源
最近更新 更多