提问人:Alex carrasco 提问时间:2/3/2021 最后编辑:Moaz El-sawafAlex carrasco 更新时间:5/29/2022 访问量:425
如何修复以下错误java.lang.ArrayIndexOutOfBoundsException
How to fix the following error java.lang.ArrayIndexOutOfBoundsException
问:
我想问一个已经磨碎了 ja 的代码问题,我有以下代码,我正在通过一个 10x5 数组来填充它,用数字 1 填充它,到 49 为原语,负责制作票证的函数给了我非常罕见的错误。索引:从理论上讲,该功能不必走开,但如果有人可以打我,我不知道该怎么办。
// It is this part that gives me an error, I have a fly
int ,c=0;
int m[][]= new int[10][5];
for (int i=0;i<m.length;i++) {
for (int x=0;x<m.length;x++,i++) {
m[x][i]=c;
}
}
// This part of code I only have to check if the data output
// does them correctly
for(int i=0;i<m[0].length;i++) {
for(int x=0;x<m.length;x++) {
System.out.print(" "+m[i][x]+" ");
}
System.out.println(" ");
}
}
El error que me da es siguiente:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at provas/provas.main.main(main.java:11)
答:
0赞
Oleg Cherednik
2/3/2021
#1
看起来你想用 中的数字填充给定的数组。所以你必须注意:1 to 49
int[][] arr = new int[10][5]
使用 和 创建一个数组int
10 rows
5 columns
arr.length
给你一个总计rows amount
arr[0].length
给你一个总数(每行可以有不同的长度)。columns amount
row 0
public static int[][] fillArray(int[][] arr) {
int i = 1;
for (int row = 0; row < arr.length; row++)
for (int col = 0; col < arr[row].length; col++)
arr[row][col] = i++;
return arr;
}
最后打印一个数组:
public static void printArray(int[][] arr) {
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++)
System.out.format("%3d", arr[row][col]);
System.out.println();
}
}
你原来的方法可以是这样的:
int[][] arr = fillArray(new int[10][5]);
printArray(arr);
评论