我有一点问题,希望你能帮助我:
我在java中有一个叫做TOKEN的类,里面有这个:
public enum TOKEN { EMPTY, WHITE, BLACK }
在其他类(同一个包)中,我试图创建一个包含列和行的数组矩阵,并且我试图用值" EMPTY"来初始化它。来自其他班级" TOKEN":
public class Board {
private int row;
private int column;
private TOKEN[][] board;
public Board(int nr, int nc){
this.row = nr;
this.column = nc;
for(int a=0; a < row; a++)
{
for(int b=0; b < column; b++)
board[a][b] = TOKEN.EMPTY;
}
}
NR和NC是整数并且具有值(例如6,7)但是当我尝试运行代码时,它在此处停止(第一次迭代)
董事会[a] [b] = TOKEN.EMPTY;
有人可以帮我吗?谢谢!
答案 0 :(得分:3)
您必须先初始化数组:
board = new TOKEN[nr][nc];
答案 1 :(得分:2)
您需要先使用board
初始化new TOKEN[nr][nc]
变量:
public class Board {
private final int row;
private final int column;
private final TOKEN[][] board;
public Board(int nr, int nc) {
this.row = nr;
this.column = nc;
// here we initialize the array, otherwise board will be null
board = new TOKEN[nr][nc];
for (int a = 0; a < row; a++) {
for (int b = 0; b < column; b++) {
board[a][b] = TOKEN.EMPTY;
}
}
}
public static void main(String[] args) {
Board board = new Board(10, 10);
}
}
答案 2 :(得分:0)
缺少初始化:
...
board = new TOKEN[row][column]; // <---
for(int a=0; a < row; a++)
...
答案 3 :(得分:0)
在构造函数Board
中,您需要首先初始化数组,然后才能用空标记填充它:
public Board(int nr, int nc) {
board = new TOKEN[nr][nc]; // initializes the matrix with nr arrays of nc size
this.row = nr;
this.column = nc;
for (int a = 0; a < row; a++) {
for (int b = 0; b < column; b++) {
board[a][b] = TOKEN.EMPTY;
}
}
}
答案 4 :(得分:0)
你隐瞒了你得到的错误:NullPointerException
。你得到这个例外是因为你忘了初始化你的数组:
public Board(int nr, int nc){
this.row = nr;
this.column = nc;
this.board = new TOKEN[nr][nc]; // <-- here
for(int a=0; a < row; a++) {
for(int b=0; b < column; b++)
board[a][b] = TOKEN.EMPTY;
}
}