簡體   English   中英

在 Java 中填充 2D 數組並獲取 ExceptionOutOfBounds

[英]Filling 2D Array in Java and getting ExceptionOutOfBounds

我搜索了一些條目,但自己無法正確回答我的問題。

我正在嘗試用值填充二維數組。 作為測試,我目前正在嘗試用整數 1 填充數組。

我不明白我的錯誤。

public static void creatBoard () { 
        
        final int L = 6; 
        final int H = 6; 
        
        // Modell: 
        
        int [] [] board = new int [L] [H]; 
        for (int i = 0; i<=board.length; i++) {
            for (int j = 0; j<=board.length; j++) {
                board [i] [j] = 1; 
            }
            System.out.println("");
            
            
        }

使用索引 0 到 length-1(因為數組索引從 0 開始)

    public static void creatBoard () { 
            
            final int L = 6; 
            final int H = 6; 
            
            // Modell: 
            
            int [] [] board = new int [L] [H]; 
            for (int i = 0; i<board.length; i++) {
                for (int j = 0; j<board[i].length; j++) {
                    board [i] [j] = 1; 
                }
                System.out.println("");           
            }
}

只需調試它,您就可以看到,

for (int i = 0; i<=board.length; i++) {
        for (int j = 0; j<=board.length; j++) {
            board [i] [j] = 1; 
        }
        System.out.println("");
        
        
    }

i 和 j 將值從 0 更改為 6,這意味着它超出了 arrays 范圍(您迭代 7 個元素,而不是 6 ),只需刪除=登錄循環體

for (int i = 0; i<board.length; i++) {
        for (int j = 0; j<board[i].length; j++) {
            board [i] [j] = 1; 
        }
        System.out.println("");     
    }

您的板陣列大小為 6x6,因此board.length為 6。

當您為 (int j = 0; j<=board.length; ij+)運行循環時,它將從 0 運行到 6,但數組索引是從 0 到 5。所以當 j=6 時,會發生ExceptionOutOfBounds ,因為它會指的是索引板[0][6]

將兩個循環中的條件從<=board.length 更改<board.length

暫無
暫無

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

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