Search code examples
javaarraysmultidimensional-arrayindexoutofboundsexception

Arrayindexoutofbounds in an 2d array java


I'm trying to get the default null values out of my 2d String array.

I've got this so far.

String[][] sterren = new String[12][37];
    int h = 12;
    String leeg = "";       
    while(h > 0){ 
        int b = 37;
        sterren[h][b] = leeg;
        while(b > 0){
            sterren[h][b] = leeg;
            b = b-1;
        }
        h = h-1;
    }       

with h = height and b = width

When I try to execute this I get an arrayindexoutofbounds 12 on the line sterren[h][b] = leeg;. why is that since I clearly made 12 columns and 37 rows.


Solution

  • new String[12][37] means that the length of each array is 12 and 37, they can hold 12 and 37 Objects respectively. Because arrays start at index 0 that means they only have indexes 0 - length - 1. That means if an array has a length of 12, it has indexes 0-11. In this example you try adding to index 12 in the outer array and index 37 to the inner arrays (in which their last index is 36).

    To make this work have h = 11 and b = 36 and make the while loops while h >=0 and while b >= 0.