[英]How to create rectangular 2d array in Java?
I'm trying to create a minesweeper clone for school and looking to create a variable board size, the below code works to create a 2d minefield but I get an arrayIndex out of bounds error when columns != rows.我正在尝试为学校创建一个扫雷艇克隆并希望创建一个可变的板尺寸,下面的代码可以创建一个二维雷区,但是当列!= 行时,我得到一个 arrayIndex 越界错误。 Any help would be appreciated.任何帮助,将不胜感激。 Amateur code so any other advice is welcome.业余代码,因此欢迎任何其他建议。
public void genBoard(int columns, int rows) {
board = new Tile[rows][columns];
for (int y = 0; y < rows; y++) {
for (int x = 0; x < board[y].length + 1; x++) {
board[x][y] = new Tile(x, y, 0, false);
}
}
}
x < board[y].length + 1;
should be应该
x < board[y].length;
That is what is causing the index out of bound error.这就是导致索引越界错误的原因。
But also, board[x][y]
should be board[y][x]
而且, board[x][y]
应该是board[y][x]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.