2014-04-04 120 views
0

我想檢查單元格的狀態是否爲真值。如果狀態爲真,那麼我將保存元素的X和Y(2D陣列)。下面是我使用的方法,其中C是計算有多少細胞是真正的計數器:Java:NullException對象指針[]

public void checkState(){ 
     System.out.println("Checking State"); 
     int c = 0; 

     for(int y = 0; y < GRID_Y; y++){ 
      for(int x = 0;x < GRID_X; x++){ 
       if(state[x][y]==true){ 
        //Error starts after this line 
        coords[c].setX(x); 
        coords[c].setY(y); 
        c++; 

        //DEBUG 

         System.out.println(coords.getX()); 
         System.out.println(coords.getY()); 
       } 

      } 
     } 
     System.out.println(c); 
    } 
} 

的COORDS對象聲明如下:

private Coords[] coords = new Coords[totalCells];

(試圖改變totalCells到一個小的整數像10值,仍然沒有工作)

哪裏COORDS類是:

public class Coords { 
    int x,y; 

    public Coords(){ 
     x = 0; 
     y = 0; 
    } 

    public void setX(int xIn){ 
     x = xIn; 
    } 

    public void setY(int yIn){ 
     y = yIn; 
    } 

    public int getX(){ 
     return x; 
    } 

    public int getY(){ 
     return y; 
    } 

} 

我收到以下錯誤:

Checking State 
java.lang.NullPointerException 
    at game.GameOfLifeGUI.checkState(GameOfLifeGUI.java:116) 
    at game.GameOfLifeGUI.<init>(GameOfLifeGUI.java:57) 
    at game.GameOfLifeGUI$1.run(GameOfLifeGUI.java:32) 
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) 
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) 
    at java.awt.EventQueue.access$200(Unknown Source) 
    at java.awt.EventQueue$3.run(Unknown Source) 
    at java.awt.EventQueue$3.run(Unknown Source) 
    at java.security.AccessController.doPrivileged(Native Method) 
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) 
    at java.awt.EventQueue.dispatchEvent(Unknown Source) 
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) 
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) 
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) 
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) 
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) 
    at java.awt.EventDispatchThread.run(Unknown Source) 

我不知道如何傳遞空值,因爲我存儲for循環的x和y。

謝謝你的時間。

+0

你是否實例化了Coords []'數組的每個'Coords'? –

+0

'私人Coords [] coords =新Coords [totalCells];'創建一組空值。這就是爲什麼你得到NPE錯誤。您需要在創建後填寫它。 – Danstahr

+0

是的,這是問題。我有一陣腦f。謝謝。 – Trifecta

回答

3

之後:private coords [] coords = new Coords [totalCells];

地址:

for(int index = 0; index < totalCells-1; index++){ 
    coords[index] = new Coords(); 
} 

這應該做的伎倆

+0

是的,當我使用對象數組時,我總是忘記這麼做。 – Trifecta

+0

你完全正確。但讓我們希望他有一個gridX * gridY == totalCell。或者他將再次發佈ArrayOutOfBoundExeption:D – JajaDrinker

+0

是的,我確實有:) – Trifecta

1

雖然@ user3497004的答案是罰款的Java < 8,你應該更喜歡:

Arrays.setAll(coords, n -> new Coords()); 

爲Java 8(以及可能以上,讓我們成爲未來主義者)。

+0

n代表什麼?從未使用數組類tbh。 – Trifecta

+0

n是被初始化的特定單元的索引 – m09