为什么我的BigInteger.add()得到NullPointerException?

时间:2012-04-26 10:59:02

标签: java nullpointerexception biginteger pascals-triangle

我正在尝试将Pascal Triangle打印到一百行,但Java的int似乎返回负值。我正在尝试使用BigInteger,但每当我添加两个数字时,我会得到NullPointerException!我想我初始化了它们。这是我的代码:

    import java.math.BigInteger;
    public class Pascal {
    public static void main(String[] args) { 
        BigInteger[][] p = new BigInteger[100][];

        p[0] = new BigInteger[3];
        p[0][1] = BigInteger.ONE;
        for (int i = 1; i <= N; i++) {
            p[i] = new BigInteger[i + 3];
            for(int j = 0; j < p[i].length; j++){
                p[i][j] = new BigInteger("0");
            }
            for (int j = 1; j < p[i].length - 1; j++)
                p[i][j] = p[i-1][j-1].add(p[i-1][j]); //NPE!

        }
        for (int i = 0; i <= N; i++) {
            for (int j = 1; j < p[i].length - 1; j++) {
                System.out.print(p[i][j] + " ");
            }
            System.out.println();
        }
    }
    }

3 个答案:

答案 0 :(得分:3)

考虑第一次迭代:

        for (int j = 1; j < p[i].length - 1; j++)
            p[i][j] = p[i-1][j-1].add(p[i-1][j]); //NPE!

p[i-1][j-1]解除引用p[0][0],据我所见,尚未初始化。

答案 1 :(得分:0)

这些方面很关注:

    p[0][1] = BigInteger.ONE;
    for (int i = 1; i <= N; i++) 

您正在初始化[0][1]但不是[0][0]并且您正在索引1而不是0开始循环(数组的索引为0)。

考虑应该进入的位置[0][0]以及数组循环应该如何开始。

答案 2 :(得分:0)

声明引用名称和类型是不够的;你必须为引用指定内存指向。

这是阵列的经典之作。我看到很多人声明这样的数组,并想知道为什么他们在尝试使用它时会得到NullPointerException:

int numValues = 10;
Integer [] values = new Integer[numValues];  // All ten of these references initially point to null
// You have to point them to something
for (int i = 0; i < numValues; ++i) {
    values[i] = new Integer(i);
}