2015-10-17 90 views
0

試圖訪問三角形陣列時空指針異常我試圖訪問我的三角陣列分別使用一種方法,每次我嘗試使用tarray[i][j]我得到一個空指針異常,除非它是在創建類,例如我有一個get方法,並使用return tarray[0][0],它只是拋出我的錯誤,即使它在創建內打印出來的罰款。當試圖訪問方法

我知道我可能做一些愚蠢的,但我無法弄清楚,

public class Triangular<A> implements Cloneable 
{ 

    private int inRa; 
    private A [][] tarray; 

    /** 
    * Constructor for objects of class Triangular 
    * @param indexRange - indices between 0 and indexRange-1 will be legal to index 
    *      this a triangular array 
    * @throws IllegalArgumentException - if indexRange is negative      
    */ 
    public Triangular(int indexRange) throws IllegalArgumentException 
    { 
     inRa=indexRange; 
     int n = inRa; 
     int fill = 1; 
     Object [][] tarray = new Object [inRa + 1][]; 
      for (int i = 0; i <= inRa; i++){ 
      tarray[i] = new Object [n]; 

      } 

      for (int i = 0; i < tarray.length; i++){ 

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

     for (int i = 0; i < tarray.length; i++) { 
     for (int j = 0; j + i < tarray[i].length; j++){ 
     System.out.print(tarray[i][j + i] + " "); 
     } 
     System.out.println(); 

     } 

    } 
} 

感謝您的幫助!

回答

1

您不會初始化任何內容到tarray字段在構造函數中,您初始化一個具有相同名稱的局部變量;這一個:

Object [][] tarray = new Object [inRa + 1][]; // doesn't access the tarray field 

你必須然而,一些分配給tarray領域,以固定NPE。

順便說一句:最好不要使用與字段名稱相同的局部變量。

+0

謝謝!這是固定的,是的,我應該已經意識到,我正在初始化它作爲一個新的變量 – Identicon