Skip to content
Advertisement

2D Array work, out of bounds error, for loop,

One of my school works tells us to make an 2D array, and display what is in the array. I don’t know why it is saying out of bounds, and am kind of stuck. What we where tasked to do is to make, 10 student IDs and 3 tests with scores for each of them, as shown below in the first row of the Array. The for loop part was designed to move on to the next column after x reaches 3 (when the final test score is displayed).

public class TwoDArray {
public static void main(String [] args) {
    int [] [] musicScores = { {1001, 2002, 3003, 4004, 5005,6006,7007,8008,9009,1010,},{10,7,8,9,5,10,8,7,6,9},{9,8,10,9,9,10,9,9,7,9},{8,7,8,9,8,7,8,10,8,8}};
    int y = 0;
    for (int x = 0; x < 4; x++) {
        System.out.print(musicScores[x][y] + "t");
        for (x = 3;y < 10; y++) {
            x = 0;
            System.out.println("");
            }
        }
    }
}

Advertisement

Answer

Your problem is that for the line:

System.out.print(musicScores[x][y] + "t");

you are allowing y to take on a value of 10, which an invalid array index. The reason for this is that you are using y after you have exited the for loop:

for (y = 0;y < 10; y++) {
    ...
}

When this loop exits, y is 10. You then loop around and use y outside of that loop, which you probably shouldn’t be doing. I’m not sure exactly what you’re trying to do, but maybe you want to move the problematic line inside your inner for loop, like this:

class TwoDArray {
    public static void main(String [] args) {
        int [] [] musicScores = { {1001, 2002, 3003, 4004, 5005,6006,7007,8008,9009,1010,},{10,7,8,9,5,10,8,7,6,9},{9,8,10,9,9,10,9,9,7,9},{8,7,8,9,8,7,8,10,8,8}};
        for (int x = 0; x < 4; x++) {
            for (int y = 0;y < 10; y++) {
                System.out.print(musicScores[x][y] + "t");
            }
            System.out.println();
        }
    }
}

NOTE: Both my answer and the one supplied by @Dren clean up your code quite a bit. Setting x = 0 was doing you no good, and if you only use y inside the inner for loop, which you probably should be doing, then its best to define y in the for loop itself to make sure you don’t use it outside the loop. All that your inner for loop is doing in your original code is printing a bunch of empty lines. I doubt that’s what you intended. Neither of our solutions prints blank lines.

@Dren’s answer does something quite noteworthy…it replaces hard-coded constants for array lengths with the actual lengths of the arrays in your dataset. This is always preferable. If you do this, then when you change your dataset, you don’t have to make sure you change the hard coded length values to match…something that is quite error prone.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement