NullPointerException,锯齿状数组

时间:2014-03-30 16:28:57

标签: java exception

当我想引用构造函数之外的数组元素时,程序会抛出NullPointerException (location: function ratio)

private int tabPascal[][];


Pascal(int n){
    int tabPascal [][]= new int[n+1][];

    for(int i = 0; i <= n; i++){
        tabPascal[i] = new int[i+1];
    }


    for(int i = 0; i < tabPascal.length; i++){
        for(int j = 0; j<tabPascal[i].length; j++){

            tabPascal[i][j] = binomial(i,j);
            System.out.print(tabPascal[i][j] + "  ");
        }
        System.out.println();
    }

}

...

   public int ratio(int n, int k){

    return tabPascal[n][k];
}

1 个答案:

答案 0 :(得分:6)

您的构造函数中的shadowing实例变量。因此,它从未被初始化。

private int tabPascal[][];


Pascal(int n){
    tabPascal = new int[n+1][];  
    ....
}