gpt4 book ai didi

Java,关于使用对象数组的 NullPointerException

转载 作者:行者123 更新时间:2023-11-30 06:10:02 25 4
gpt4 key购买 nike

这是代码示例。我想创建一个一维对象数组,给它们赋值,在其他方法中使用它,然后将它作为二维数组打印出来。

起初我想打印起始板,但是当我尝试循环遍历数组时出现 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
}
}
}
}

最佳答案

您没有构建电路板。在遍历成员之前执行 board.boardBuilder()

board.boardBuilder()
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
}
}

关于Java,关于使用对象数组的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36670520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com