سؤال

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();
        }
    }
    }
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

These lines are concerning:

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

You are initialising [0][1] but not [0][0] and you are starting your loops at index 1 not 0 (arrays are indexed at 0).

Consider what should go into position [0][0] and how the array loops should start accordingly.

Declaring a reference name and type isn't sufficient; you have to allocate memory for the the reference to point to.

It's a classic with arrays. I see a lot of people who declare an array like this and wonder why they get NullPointerException when they try to use it:

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);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top