PigeonMilk Stories
PigeonMilk Stories

Reputation: 65

2D index-Array out of bounds

For the sake of testing if my logic works(I think It should but Its not) I am doing small operations in a paint method, I just didn't want to mess my main project up.

I have X and Y positions of Tiles on a board and want to just make sure I have the right X and Y so I made this method:

private void drawBoard(Graphics2D g2d) throws IOException {
    BufferedImage image = ImageIO.read(getClass().getResourceAsStream("/background.png"));
    g2d.drawImage(image,0,0, null,null);
    int col = 2;
    int rows = 6;
    int[][] RedArray =
        {{274, 399},
        {274, 440},
        {274, 480},
        {274, 520},
        {274, 560},
        {274, 600}};

    for(int i = 0; i < col; i++){
        for(int j = 0; i < rows; j++){
            g2d.drawRect(RedArray[rows][col], RedArray[rows][col], 25, 25);
        }
    }

}

this is supposed to get the x,y values from the RedArray and then paint them onto the board but I am getting an index out of bound error and I can't seem to kick it

Upvotes: 0

Views: 58

Answers (3)

Cameron637
Cameron637

Reputation: 1719

In your second for loop you have i < rows, needs to be j < rows like so:

for (int j = 0; j < rows; j++)

Also RedArray[rows][col] should be RedArray[j][i]

Upvotes: 2

Arjun Bala
Arjun Bala

Reputation: 287

I think you want to do something like this

private void drawBoard(Graphics2D g2d) throws IOException {
BufferedImage image = ImageIO.read(getClass().getResourceAsStream("/background.png"));
g2d.drawImage(image,0,0, null,null);
int col = 2;
int rows = 6;
int[][] RedArray =
    {{274, 399},
    {274, 440},
    {274, 480},
    {274, 520},
    {274, 560},
    {274, 600}};

for(int i = 0; i < col; i++){
    for(int j = 0; j < rows; j++){
        g2d.drawRect(RedArray[j][i], RedArray[j][i], 25, 25); // not RedArray[rows][cols]
    }
}

}

Upvotes: 0

dsh
dsh

Reputation: 12214

RedArray[rows][col]

You want i and j here, not rows and col.

Upvotes: 2

Related Questions