全部,Java - 如何將table [i] [j]元素聲明爲實例變量?
我想編碼一個Connect4遊戲。爲此,我創建了一個P4Game類和一個代表Connect4板的i X j尺寸的P4Board類。
在P4Game,我有以下幾點:
public class P4Game{
//INSTANCE VARIABLES
private int nbLines;
private int nbColumns;
private P4Board [][] position;
//CONSTRUCTOR
public P4Game(int nbLines, int nbColumns){
this.nbColumns = nbColumns;
this.nbLines = nbLines;
P4Board [][] position = new P4Board [nbLines][nbColumns]; //Creates the table to receive the instances of the P4Board object.*/
for (int i=0; i<nbLines; i++){
for (int j=0; j<nbColumns; j++){
this.position[i][j] = new P4Board(i,j); //Meant to create each object at (line=i, column=j)
}
}
}
這導致了嵌套循環,我提this.position[i][j]
一個NullPointerException。我在這個類的其他方法中引用這些對象,所以我需要它們作爲實例變量。我想這個例外是因爲我沒有在表的開始處列出表元素position[i][j]
作爲實例變量。 (1)我的假設是正確的,如果是這樣的話(2)將聲明這種形式的實例變量的語法是什麼?
謝謝大家的幫助,我認識到的是一個非常基本的問題。希望它也會使其他新手受益。
乾杯,
JDelage
給出整個堆棧跟蹤 – Bozho 2010-03-28 16:51:30
它被稱爲一個字段,而不是一個實例變量。 – SLaks 2010-03-28 16:52:26
我見過很多地方使用的「實例變量」。它出什麼問題了? – 2010-03-28 16:56:55