[英]2D array filling | ArrayIndexOutOfBoundsException error
下午好! 大家好! 第一次发帖
对于我的作业,我们使用算术和嵌套 for 循环填充数组。 在使用素数之前,我已经完成了一个 2D 数组的完整填充,尽管我认为我在某个地方搞砸了..
当做这行时int priorNum = arr[r-1][c];
(请参阅下面的完整代码)我遇到了异常。 我正试图用这个新方程覆盖数组中的其他行,但我必须被这个极其无礼的 Java 错误所阻止。
错误: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 10
我的数组: int[][] arrayDimension = new int[10][6];
public static void populate2D (int[][] arr) {
//hardcode in values first :)
//and then peek up one row, but you can't go above the original row
arr[0][1] = 10;
arr[0][2] = 100;
arr[0][3] = 500;
arr[0][4] = 1000;
arr[0][5] = 5000;
int count = 0;
//for each row..
for (int r = 0; r < arr.length; r++) { //for each row
for ( int c = 0; c < arr[r].length; c++) { //for each column
arr[r][0] = count;
//never navigate out of bounds
//row 0 is where we're at.. how to populate further rows..?
int priorNum = arr[r-1][c];
int nextNum = priorNum * 2;
arr[r][c] = nextNum;
//can't look back .. SO go UP one.. which is r - 1 goes back one.. and then the length goes - 1
//when c is - peek UP a row < and enter last column.. ^
}
count++;
}
}
如果你能理解我想要做什么,我会留下一些我写的笔记:)
我还可以提供我为您想尝试的任何测试编写的这个 printArray 方法!
public static void print2DArray(int[][] arr) {
for ( int r = 0; r < arr.length; r++) {
for ( int c = 0; c < arr[r].length; c++) {
System.out.print(arr[r][c] + "\t");
}
System.out.println();
}
}
}
感谢您的任何回复/帮助! 这里的每个人似乎都很好,我找不到与我的答案有关的问题类型,所以我对发布感到难过,呵呵
我可以看到的问题是,在第一次迭代中,当int priorNum = arr[r-1][c];
被执行, r = 0
,由您的外部 for 循环指定。
因此,您基本上是在尝试使用负索引访问二维数组的元素,这将导致抛出ArrayIndexOutOfBoundException
。
您可以采用处理第一次迭代的 if 语句,这样您就不会访问先前的索引。
您还可以查看以下文章的数组访问部分: https : //docs.oracle.com/javase/specs/jls/se7/html/jls-10.html
希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.