[英]why there is an (java.lang.ArrayIndexOutOfBoundsException: 5) exception when I try to run this program?
public class number_of_islands {
public static void main(String[] args) {
number_of_islands tester = new number_of_islands();
char[][] testData = {{'1', '1', '1', '1', '0'},
{'1', '1', '0', '1', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '0', '0', '0'}};
System.out.println(tester.numIslands(testData));
}
public int numIslands (char[][] grid) {
if (grid == null || grid.length == 0) {
throw new IllegalArgumentException("Invalid argument");
}
int res = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; i < grid[i].length; j++) {
if ((grid[i][j] == '0')
/* the line below is where the above error occurs */
||((i > 0) && (grid[i - 1][j] == '1'))
|| ((j > 0) && (grid[i][j - 1] == '1'))) {
continue;
}
res++;
}
}
return res;
}
}
In the code above, the numIslands function accepts an 2-d array as the input and compute something, but there is an array out of bounds error in the line below the comment, I have checked to let i > 0 and j > 0, why the question still there? 在上面的代码中,numIslands函数接受一个二维数组作为输入并计算内容,但是在注释下方的行中有一个超出范围的错误,我检查了让i> 0和j> 0,为什么问题仍然存在?
Thanks! 谢谢!
Just make these small changes in for loops 只需在for循环中进行这些小的更改
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
...
Your condition in the second for loop was "i < grid[i].length" 您在第二个for循环中的条件是“ i <grid [i] .length”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.