我想檢查單元格的狀態是否爲真值。如果狀態爲真,那麼我將保存元素的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。
謝謝你的時間。
你是否實例化了Coords []'數組的每個'Coords'? –
'私人Coords [] coords =新Coords [totalCells];'創建一組空值。這就是爲什麼你得到NPE錯誤。您需要在創建後填寫它。 – Danstahr
是的,這是問題。我有一陣腦f。謝謝。 – Trifecta