0

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah that makes sense thanks! Didn't know that the 0 was counted as an index automatically.
The first dimension doesn't hold strings at all, but rather holds arrays of strings. Conceptually it may help to think about it like a table where the first index specifies a row, and the second index specifies a column in that row. You may prove this by doing the following: String[][] table = new String[12][37]; String[] row = table[0]; String value = row[0]; Java also supports ragged arrays, which means that the second dimension doesn't need to be fixed when the array is created (each row could be a different length).
@BobbyStJacques Thanks for pointing that out. I was just making a point about the length and wrote it too quickly. I'll correct it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.