-2
import java.math.BigInteger;

public class PascalsTriangle {

    public int row = 0;
    public BigInteger[][] pascal = new BigInteger[ (int) (row +1)][];

    public PascalsTriangle(int dimension) {
        row = dimension + 2;
        pascal  = new BigInteger[row +1][];
        pascal[1] = new BigInteger[1 + 2];
        pascal[1][1] = new BigInteger("1");

        for (int i = 2; i <= row; i++) {
            pascal[i] = new BigInteger[i + 2];

            for (int j = 1; j < pascal[i].length - 1; j++) {
                pascal[i][j] = pascal[i - 1][j - 1].add(pascal[i-1][j]) ;
            }
        }
    }

    public BigInteger getface(int row, int column) {
        return pascal[row][column]; 
    }
}

I was trying to print a pascals triangle but the integer requirement for me is very high, i.e more than the max value of long, so I used BigInteger. But I'm getting a NullPointerException at the part where I add BigIntegers in the class PascalsTriangle. Is this the right way to add a 2 dimensional BigInteger array?

James Dunn
  • 8,064
  • 13
  • 53
  • 87

1 Answers1

1

the null pointer is not from the BigInteger.add

it's from the array index

man-r
  • 208
  • 3
  • 14
  • How do i Minimize this error – Lakshmana Deepesh Dec 25 '15 at 19:32
  • @Deepesh, by not indexing beyond the bounds of the array. Make sure you know what values `i` and `j` have everywhere, and the sizes and content of your arrays (especially the arrays that point to other arrays) – The Archetypal Paul Dec 25 '15 at 19:47
  • It was was working properly when i just had long arrays.but when I changed it to the biginteger I started getting the null pointer exception. – Lakshmana Deepesh Dec 25 '15 at 19:54
  • If you say so. Post both versions. – The Archetypal Paul Dec 25 '15 at 21:56
  • t's because in `pascal[i][j] = pascal[i - 1][j - 1].add(pascal[i-1][j]), the first time through the loop,` j == 1`, so `j -1 == 0` but you've not assigned a `BigInteger` value to the zero'th element of the array so it just contains `null`. It works for `long`, because they're primitives, not objects, and default to zero. – The Archetypal Paul Dec 25 '15 at 22:08