Search code examples
javanullpointerexceptionbigintegerpascals-triangle

Why does my BigInteger.add() get a NullPointerException?


I'm trying to make a Pascal Triangle print to a hundred rows, but Java's int seems to return negative values. I'm trying to use BigInteger, but I get NullPointerException whenever I add two numbers! I think I initialized them. Here is my code:

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

Solution

  • Consider the very first iteration of:

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

    The p[i-1][j-1] dereferences p[0][0], which as far as I can see has not been initialized.