全部,
我正在尝试编写 Connect4 游戏代码。为此,我创建了一个 P4Game 类和一个 P4Board 类,它们代表 Connect4 板的 i X j 尺寸。
在 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)声明这种形式的实例变量的语法是什么?
感谢大家的帮助,我意识到这是一个非常基本的问题。希望它也能让其他新手受益。
干杯,
杰拉格
最佳答案
请参阅内联添加的注释...您的代码很好,除了一个小细节,您正在创建一个新的 position
变量,您实际上打算在其中使用实例变量。
public class P4Game{
//INSTANCE VARIABLES
private int nbLines;
private int nbColumns;
private P4Board [][] position;
//CONSTRUCTOR
public P4Jeu(int nbLines, int nbColumns){
this.nbColumns = nbColumns;
this.nbLines = nbLines;
// You're creating a LOCAL variable called position here if you don't comment what's commented:.
/*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)
}
}
}
}
关于Java - 如何将 table[i][j] 元素声明为实例变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2533670/