【问题标题】:Why a NPE in 2d Array?为什么在二维数组中使用 NPE?
【发布时间】:2012-02-23 13:35:55
【问题描述】:

为什么我会在以下任务中获得 NPE:

    mPyramid[row][column] = temp;

这是我的代码:

    Block temp;
    Block[][] pyramid = new Block[mInput.length][];

    for (int i = 0; i < pyramid.length; i++) {
        pyramid[i] = new Block[mInput[i].length];
        for (int j = 0; j < pyramid[i].length; j++) {
            pyramid[i][j] = new Block();
        }
    }

    for (int row = 1; row < mInput.length; row++) {
        for (int column = 0; column < mInput[row].length; column++) {
            temp = new Block(mInput[row][column], null, null);
            mPyramid[row][column] = temp;

            setParents(row, column);
            temp.setPathNode(calculateDistance(temp));

        }
    }
}

【问题讨论】:

  • 我没有看到mPyramid的任何声明。

标签: java multidimensional-array nullpointerexception


【解决方案1】:

因为mPyramid 未初始化或子数组mPyramid[row] 未初始化。

我猜你属于第二种情况。要立即使用高度和宽度初始化 mPyramid,您可以使用:

mPyramid = new Block[height][width]; // Swap height and width if you prefer

【讨论】:

    【解决方案2】:

    您似乎正在创建局部变量pyramid,然后引用mPyramid

    【讨论】:

    • 谢谢,只需要第二双眼睛就能看到。将被接受的答案。
    猜你喜欢
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2021-12-28
    相关资源
    最近更新 更多