2017-01-02 56 views
1

我懷疑makeLine方法以某種方式創建了一個null數組,但我不太確定。Android:nullpointerexception試圖從空數組讀取

任何幫助將不勝感激!我的代碼片段如下:

public void all() { 

     int[][] line = new int[3][]; 

     for (int i = 0; i < 3; i++) { 
      if (i > 0 && line[i - 1][0] == 2) { // Error occurs at this line 
       int start = line[i - 1][2]; 
       int pos = line[i - 1][1]; 
       int xy = line[i - 1][3]++; 

       if (line[i - 1][3] == 1) { 
        int end = y()[1]; 
        line[i] = new int[]{1, start, end, pos, xy}; 
       } else { 
        int end = x()[1]; 
        line[i] = new int[]{1, start, end, pos, xy}; 
       } 
      } else { 
       line[i] = makeLine(); 
      } 
     } 
} 

private int[] makeLine() { 
       Random r = new Random(); 

       int startX = x()[0]; 
       int endX = x()[1]; 
       int startY = y()[0]; 
       int endY = y()[1]; 

       int xy = r.nextInt(3 - 1) + 1; 

       if (xy == 1) { 
        return new int[]{1, startX, endX, startY, xy}; 
       } 

       return new int[]{1, startY, endY, startX, xy}; 
      } 

private int[] x() { 
     DisplayMetrics displaymetrics = context.getResources().getDisplayMetrics(); 
     int xLeft = (int) (13 * displaymetrics.density); 
     int xRight = (int) (displaymetrics.widthPixels - (13 * displaymetrics.density)); 

     Random r = new Random(); 
     int startX = r.nextInt(xRight - xLeft) + xLeft; 
     int endX = r.nextInt(xRight - xLeft) + xLeft; 

     return new int[]{startX, endX}; 
    } 

private int[] y() { 
     DisplayMetrics displaymetrics = context.getResources().getDisplayMetrics(); 
     int yTop = (int) (60 * displaymetrics.density); 
     int yBottom = (int) (displaymetrics.heightPixels - (51 * displaymetrics.density)); 

     Random r = new Random(); 
     int startY = r.nextInt(yBottom - yTop) + yTop; 
     int endY = r.nextInt(yBottom - yTop) + yTop; 

     return new int[]{startY, endY}; 
    } 
+1

你能發佈你得到的完整的錯誤/堆棧跟蹤? –

+0

我不認爲這裏有足夠的信息來幫助你。您需要爲我們提供一個我們可以運行的完整示例。目前這是不可能的,因爲某些方法(例如'x()'和'y()')缺失。 –

回答

0

我想你會得到一個空指針,因爲你引用了一個超出數組邊界的元素。在那裏你上了錯誤的行應該是這樣的:

if (i > 0 && line[i][0] == 2) { 

相反的:

if (i > 0 && line[i - 1][0] == 2) 

有遍佈這個方案類似這樣的錯誤。請記住,數組在0開始索引,而不是1.

+0

如果內存已分配,訪問行[i - 1] [0]或訪問行[i] [0]沒有任何問題。 – yakobom

1

這是一個例外,因爲您在初始化之前嘗試訪問line [0] [0],這裏沒有任何內容。

這樣做:

int[][] line = new int[3][]; 

你只創建此多維數組的一個維。做到這一點的方法可以是:

int[][] line = new int[3][SOME_NUMBER]; 

或顯式初始化的每一行:

int[][] line = new int[3][]; 
for (int i = 0; i < 3; i++) { 
    line[i] = new int[SOME_NUMBER]; 
} 

如果您需要更好地瞭解它,看看這裏,例如:多維數組在Java

] 1