2010-07-12 99 views
1

我有以下全局陣列...奇怪的空指針異常

public static float camObjCoord[] = new float[8000]; 

我有一個方法飼用價值爲它的索引我要送他們是這樣的...

layers.addcube(-6, -2, -6, -2); 

i被一個類變量聲明爲..

int i = 0; 

和層被聲明爲...

GLLayer layers = new GLLayer(this); 

但是當我做我得到一個NullPointerException ....

public void addcube(float highx, float lowx, float highz, float lowz){ 
    //Constructing new cube... 

    cubes++; 
    float highy = 4.5f; 
    float lowy = 2.5f; 

    //FRONT 
    Global.camObjCoord[i] = highx; //null pointer here. 

沒有人有任何想法,爲什麼它給了我一個空指針?有更多的代碼,但我認爲只給你相關的東西是足夠的。

感謝

+2

後堆棧跟蹤你正在得到。 – 2010-07-12 13:20:37

+1

'i'(以及擴展名'Global.camObjCoord.length')的值是什麼? – ChrisF 2010-07-12 13:20:38

+0

@ ChrisF根據條件 – Skizit 2010-07-12 13:21:53

回答

3

嘗試將其更改爲這樣:

​​3210

當我想你somwehere更新camObjCoord並將其設置爲null。否則,我不知道如何在該行中獲得NullPointerException。

+0

爲什麼要聲明它最終解決了這個問題? – DaveJohnston 2010-07-12 13:26:53

+1

@DaveJohnston:我引用:「正如我假設你有更新camObjCoord並將其設置爲null,否則我不會看到如何在該代碼中獲得NullPointerException。」 – 2010-07-12 13:28:38

+2

@DaveJohnston - 也許是因爲你以後不能將camObjCoord設置爲null,因爲它是最終的? – 2010-07-12 13:29:30

3

你確定這是一個NullPointerException,而不是一個ArrayIndexOutOfBoundsException?如果start != 0,那麼i是數組的長度。但是,數組索引從0運行到length - 1 - 因此您需要i = Global.camObjCoord.length - 1;以在聲明引發異常的行中獲取有效的索引。

2

最高陣列指數應爲array.length - 1。因此,

if(start != 0){ 
     i = Global.camObjCoord.length - 1; 
    } 
0

您正在分配i = array.length,然後指派給i處的元素。這將訪問數組的末尾。

0

我認爲,當你使用i = Global.camObjCoord.length;,它集i = 8000,所以當你嘗試把你的價值,它把它的指數8000,這是不可能的表會從0到7999

試試這個以確保:

//FRONT 
    System.out.println('Value of index i : '+i); 
    Global.camObjCoord[i] = highx; //null pointer here. 

然後,你應該看到i的值,看看它是否超出了數組邊界。

希望我幫上忙了。

1

鑑於您顯示的代碼,不能有NullPointerException。或者異常發生在不同的行,或者它是一個不同的異常,或者你將數組設置爲null。

0

你應該發佈堆棧跟蹤,因爲我認爲它不是NullPointerException而是ArrayIndexOutOfBoundsException。如果你設置了i = Global.camObjCoord.length,那麼你不能使用i索引數組,因爲它將離開數組的末尾。想想看,如果你有一個大小爲1的數組,那麼你可以使用的唯一索引是0,如果你試圖訪問元素1,你將離開數組的末尾,從而得到一個異常。

2

請注意,如果該行在執行之前被指定camObjCoord的值,則該行可以拋出異常。這是相當苦逼這種情況,但它是可能的(例如,如果先前的初始化包含一個方法調用並訪問camObjCoord該方法內):

public class NPEThrower { 
    Object x = initX(); 
    float[] foo = new float[8000]; 

    private Object initX() { 
     int l = foo.length; 
     return "x"; 
    } 
} 

注意添加final到外地定義不解決這意味着您可以在執行期間觀察final字段的兩個不同值:null和實際值!)。

0

像inflagranti已經指出 - 在唯一的方式在這裏得到真正的NPE是有camObjCoord設置爲null

這是爲了測試它的方式:

// DEBUG Code - start 
if (camObjCoord == null) { 
    System.out.println("Who the F*** played with comObjCoord! NPE comeing next."); 
} 
if (i >= camObjCoord.length) { 
    System.out.println("There's nothing outside the array. AIOOBE thrown ... now!"); 
} 
// DEBUG Code - end 

Global.camObjCoord[i] = highx; //null pointer here.