Question

Ok, I need to have a class that re-creates the Pascal Triangle. We are using BlueJ and I can't get my arrays to access each other. Here's the code:

public class PascalTriangle {

    private int currentLineNumber;
    private int[] previousLineArray;
    private int[] nextLineArray;

    public void firstLine()
    {
        currentLineNumber = 1;
        System.out.println("1");
    }

    public void nextLine()
    {
        if (currentLineNumber == 1) {
            int [] previousLineArray = new int [(currentLineNumber+1)];
            previousLineArray[0] = 1;
            previousLineArray[1] = 1;
            System.out.println("1 1");
            currentLineNumber = 2;
        }
        else if(currentLineNumber >= 2) {
            for (int lineCount = currentLineNumber; lineCount <= currentLineNumber; lineCount++) {
                int [] nextLineArray = new int [(lineCount+1)];
                nextLineArray[0] = 1;
                System.out.print(nextLineArray[0] + " ");
                for (int nextLineCount = 1; nextLineCount < lineCount; nextLineCount++) {
                    // The next line is the line with the NullPointerException
                    nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1)
                    + previousLineArray[(nextLineCount)]]); 
                    System.out.print(nextLineArray[(nextLineCount)] + " ");
                }
                nextLineArray[(lineCount)] = 1;
                System.out.print(nextLineArray[(lineCount)] + "\n");
                previousLineArray = nextLineArray;
            }
            currentLineNumber = currentLineNumber+1;
        }
    }
}

The class will compile but as I get to the third line, which should read 1 2 1, I get a java.lang.NullPointerException at PascalTriangle.nextLine(PascalTriangle.java:29) it highlists the nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1) line. Why will the nextLineArray take the information from previousLineArray which is set when the nextLine() method is called for the first time?

Any help would be appreciated :) Thanks.

Was it helpful?

Solution

the problem is the following:

in the line where int [] previousLineArray = new int [(currentLineNumber+1)]; - you create a local array that shadows your member and only visible inside of if statement. Then when you come to this line: nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1) it uses your member array that was not init.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top