简体   繁体   中英

Filling 2D Array in Java and getting ExceptionOutOfBounds

I searched some entries, but could not answer my question correctly myself.

I'm trying to fill a 2-dimensional array with values. As a test I'm currently doing this by trying to fill the array with the int number 1.

I do not understand my mistake.

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("");
            
            
        }

Use index 0 to length-1 (as array index start with 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("");           
            }
}

just debug it and you can see, that

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

i, and j change values from 0 to 6, it means that it get's out of arrays bounds ( you iterate over 7 lements, instead of 6 ), just remove = sign in loop bodies

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

Your board array is of size 6x6 hence the board.length is 6.

When you run the loop for (int j = 0; j<=board.length; ij+) it will run from 0 up to 6 but the array indexing is from 0 to 5. So when j=6, ExceptionOutOfBounds occurs since it will be referring to index board[0][6] .

Change the condition in both the loops from <=board.length to <board.length

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM