我正在为学校做一个处理数组的项目,我遇到了一个问题。我想知道是否有人可以解释我得到的错误。这是我的代码:
public class ArrayPrinter
{
public static void main(String[] args)
{
int [] oneD = {5, 6, 7, 8 };
int[][] twoD = {{2, 4, 6, 8},
{8, 7, 9, 1},
{3, 5, 1, 2}};
int[][] twoD2 = {{1, 2},
{3, 4, 5},
{6},
{7, 8, 9}};
printArray(oneD);
printArray(twoD);
System.out.println(" ");
printArray(twoD2);
}
public static void printArray(int[] arr) {
int size = arr.length;
System.out.print("[");
for(int i=0;i< size; i++){
System.out.print(arr[i]);
if(i<size-1){
System.out.print(",");
}
}
System.out.println("]");
}
public static void printArray(int[][] arr)
{
System.out.println("[ ");
for (int row = 0; row < arr.length; row++){
System.out.print("");
for (int i = 0; row < arr[row].length; i++)
{
printArray(arr[i]);
}
System.out.println("]");
}
}
}
我在Eclipse中运行时遇到错误。这是我的输出:
[5,6,7,8]
[
[2,4,6,8]
[8,7,9,1]
[3,5,1,2]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at ArrayPrinter.printArray(ArrayPrinter.java:51)
at ArrayPrinter.main(ArrayPrinter.java:19)
如何修复此错误?你能解释一下为什么,而不仅仅是为我做这件事吗?
答案 0 :(得分:0)
您有以下代码:
System.out.println("[ ");
for (int row = 0; row < arr.length; row++) {
System.out.print("");
for (int i = 0; row < arr[row].length; i++) {
printArray(arr[i]);
}
System.out.println("]");
}
这并没有多大意义。在您的内部循环中,您引用arr[i]
,它使用int[]
索引返回i
,范围从0到arr[row]
。换句话说,它打印的行数与当前行中的元素一样多。这显然不是你想要的。
实际上,根本不需要内循环。您已经有一个打印int[]
的方法,因此您只需要遍历行。
System.out.println("[ ");
for (int row = 0; row < arr.length; row++) {
System.out.print("");
printArray(arr[row]);
}
System.out.println("]");
另请注意,如果使用for-each循环,很多代码可能会更简单:
for (int[] row: arr) {
printArray(row);
}
答案 1 :(得分:-1)
想一想你在printArray(int[][] arr)
:
for (int row = 0; row < arr.length; row++){
...
}
这会循环遍历数组的行。请记住,所有这些行都是数组。此时,arr[row]
的类型为int[]
。您有printArray
函数接受int[]
,因此请调用它。循环i
的部分是不必要的。
当您尝试访问超出范围的数组元素时,会发生IndexOutOfBoundsException
。例如:
int[] arr = {42};
arr[3] // IndexOutOfBoundsException! arr has length 1, so arr[3] is out of bounds
您收到错误是因为您尝试循环i
,但终止条件为row < arr[row].length
。这意味着在第一次迭代row
将为0.它将进入i
循环,它将检查0 < twoD2[0].length
(它是否),然后它将访问{{1} }。然后它会递增twoD2[i]
并再次执行检查,但i
尚未更新!如果在循环的条目中条件为真且您没有更改条件中使用的变量,则永远不会退出循环。因此row
永远不会停止递增,最终您尝试访问i
并获得异常。
答案 2 :(得分:-1)
打印多维数组的方法应该是:
public static void printArray(int[][] arr) {
System.out.println("[ ");
for (int row = 0; row < arr.length; row++) {
printArray(arr[row]);
}
System.out.println("]");
}