簡體   English   中英

當我嘗試運行此程序時,為什么會有(java.lang.ArrayIndexOutOfBoundsException:5)異常?

[英]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;
    }
}

在上面的代碼中,numIslands函數接受一個二維數組作為輸入並計算內容,但是在注釋下方的行中有一個超出范圍的錯誤,我檢查了讓i> 0和j> 0,為什么問題仍然存在?

謝謝!

只需在for循環中進行這些小的更改

for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid[i].length; j++) {
...

您在第二個for循環中的條件是“ i <grid [i] .length”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM