[英]Adding to 2D Array returning 'Index 0 out of bounds for length 0' error
我有一个字符串currentBoard
是#######.x+.##..w.##....#######
。 我正在尝试将字符串中的每个字符添加到二维数组中,所以它看起来像这样:
######
#.x+.#
#..w.#
#....#
######
我无法弄清楚为什么越界错误不断出现。 我已经测试过用于确定数组大小的值是否有效,我已经测试过手动添加值,例如gameboard[0][0] = '#';
这是行不通的。 这是我第一次使用多维 arrays,所以我必须做一些完全愚蠢的事情。 我就是想不通。
这是我正在使用的整个代码块:
static char[][] gameBoard = new char[currentWidth][currentHeight];
public static void generateBoard() {
int x = 0;
int y = 0;
for (int i = 0; i < currentBoard.length(); i++) {
char z = currentBoard.charAt(i);
gameBoard[x][y] = z;
if (y == currentHeight) {
y = 0;
}
if ((i + 1) % currentWidth == 0) {
x++;
}
y++;
}
}
currentHeight
为 5, currentWidth
为 6。
通过观察 x 坐标将是i
除以currentWidth
的余数,y 坐标将是i
除以currentWidth
的商(向下舍入),可以大大简化您的代码。
public static void generateBoard() {
for (int i = 0, len = currentBoard.length(); i < len; i++) {
char z = currentBoard.charAt(i);
final int x = i % currentWidth;
final int y = i / currentWidth;
gameBoard[x][y] = z;
}
}
在这里查看上面的代码。
看来board的声明中的width和height要切换一下:
public static void main(String[] args) {
String currentBoard = "#######.x+.##..w.##....#######";
char[][] board = new char[5][6];
for (int i = 0, x = 0, y = 0; i < currentBoard.length(); i++) {
board[y][x] = currentBoard.charAt(i);
x++;
if (x == board[y].length) {
x = 0;
y++;
}
}
for (char[] row : board) {
System.out.println(new String(row));
}
}
按预期打印:
######
#.x+.#
#..w.#
#....#
######
我相信您正在尝试为您的数组参数设置 static 字段,但是在您更新它们时已经创建了数组。 举个例子:
static int height; // == 0!
static int width; // == 0!
static char[][] gameBoard = new char[currentWidth][currentHeight];
public static void main(String... args) {
height = 5;
width = 6;
//but the gameboard is already made
generateBoard();
}
public static void generateBoard() {
//...
//gameboard is not valid,
}
一般来说,避免出于上述原因误用 static。 解决此问题的一种方法是使用 class 封装您的游戏板,并将宽度/高度作为 arguments。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.