好的,我需要一个可以重新创建Pascal Triangle的类。我们正在使用BlueJ,但我无法让我的阵列互相访问。
这是代码:

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


该类将编译,但是当我到达第三行时,该行应显示为1 2 1,我在java.lang.NullPointerException处得到一个PascalTriangle.nextLine(PascalTriangle.java:29),它在nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1)行中列出了高位。为什么nextLineArray将从第一次调用nextLine()方法时设置的previousLineArray中获取信息?

任何帮助将不胜感激:)谢谢。

最佳答案

问题如下:

int [] previousLineArray = new int [(currentLineNumber+1)];所在行中,您将创建一个局部数组,该数组遮蔽您的成员并且仅在if语句内部可见。然后,当您进入此行:nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1)它将使用不是init的成员数组。

10-08 11:12