我需要打印这个数组,用于为APCS编写的tic tac toe程序。我收到ArrayIndexOutOfBoundsException
。
String[][] ticBoard = {
{"-","-","-"},
{"-","-","-"},
{"-","-","-"}
};
for(int d = 0; d < ticBoard.length; d++){
for(int r = 0; r < ticBoard.length; d++){
System.out.print(ticBoard[d][r]);
}
}
答案 0 :(得分:4)
你应该将d ++更改为r ++,就像@Maroun Maroun所说的那样:
for(int d=0; d<ticBoard.length;d++){
for(int r = 0; r<ticBoard[d].length;r++){
System.out.print(ticBoard[d][r]);
}
System.out.println();
}
只是因为您的行数不等于您的列数。
答案 1 :(得分:2)
您在内循环中使用了错误的限制;你应该使用行的长度,而不是列的数量。 (由于您的二维数组没有相同数量的行和列,因此这一点尤为明显。)
因此,当您尝试访问第4个元素时,您将离开数组第一行的末尾。您的代码指定列索引ticBoard.length
的最大值(即4),这与该行中的实际项目数(即3)不对应。
这可以通过循环到行中的元素数量来修复(即ticBoard[d].length
),不数组中的行数(即ticBoard.length
)
此外,你在内循环中递增错误的值;它应该是r
,而不是d
。
for(int d = 0; d < ticBoard.length; d++) {
for(int r = 0; r < ticBoard[d].length; r++) {
System.out.print(ticBoard[d][r]);
}
System.out.println(); // So that each new row gets its own line
}
答案 2 :(得分:0)
此,
for(int r = 0; r < ticBoard.length; d++){
应该是
for(int r = 0; r < ticBoard[d].length; r++){
或者,您可以使用Arrays.deepToString(Object[])
来打印像
System.out.println(Arrays.deepToString(ticBoard));