سؤال

حسنًا ، أحتاج إلى الحصول على فصل يعيد إنشاء مثلث Pascal. نحن نستخدم 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 المعلومات من FreealLineArray التي يتم تعيينها عند nextLine() الطريقة المسمى لأول مرة؟

أي مساعدة سيكون موضع تقدير :) شكرا.

هل كانت مفيدة؟

المحلول

المشكلة هي ما يلي:

في الخط حيث int [] previousLineArray = new int [(currentLineNumber+1)]; - تقوم بإنشاء صفيف محلي يظل عضويك ومرئيًا فقط من الداخل if بيان. ثم عندما تصل إلى هذا الخط: nextLineArray[(nextLineCount)] = (previousLineArray[(nextLineCount-1) يستخدم مجموعة الأعضاء الخاصة بك التي لم تكن init.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top