这是代码示例。我想创建对象的一维数组,为它们提供值,在其他方法中使用它,然后将其打印为二维数组。
起初,我想打印起始板,但是当我尝试遍历整个数组时出现NullPointException。二维数组是一个6x6矩阵。
public class Field{
int diceCount, playerNumber;
//get and set methods etc.
}
public class Board{
public Field[] board = new Field[36];
public void boardBuilder(){
for(int i = 0; i < board.length; i++){
board[i] = new Field();
//give value to the Fields
}
}
}
public class IoMethods{
public Board board = new Board();
public void boardPrintOut(){
int helper;
for(int i = 0; i < 6; i++){
for(int j = 0; j < 6; j++){
//The next line is where it gets the Exception
helper = board.board[i*6 + j].getPlayerNumber();
//print part
}
}
}
}
原因是boardBuilder()
方法未调用。
现在,您可以先致电board.boardBuilder()
再尝试访问它,
或者更好地为Board类创建一个构造函数,例如-
Board() {
this.boardBuilder();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句