Chris V.
Chris V.

Reputation: 71

ArrayIndexOutOfBoundsException - why am I still having this problem?

I'm trying to print a chessboard to the console using a 2D array. For testing purposes, I'm trying to simply populate the board as 'x' chars. However, I keep getting an ArrayIndexOutOfBounds exception when I try to populate the array with the following:

public void setupBoard(){
        for (int i=0; i < height; i++){
            for (int j=0; j < width; j++){
                boardArray[i][j] = 'x';
            }
        }
    }

The error apparently occurs at boardArray[i][j] = 'x';

Everything seems to be in order, I dont see why this isnt working.

EDIT: I got the array to populate, but now I cannot format the printing correctly. The contents all print on one line, instead of as an 8x8 square of 'x' chars. Here's what I have now:

public void displayBoard(){
        for (int k=0; k < boardArray.length; k++)
               for (int l=0; l < boardArray[k].length; l++){
                   System.out.print(boardArray[k][l]);
               }
        System.out.println();
    }

Upvotes: 0

Views: 128

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502016

Well, presumably it's because you haven't created the board properly. Unfortunately you haven't shown us the array creation statement. It should be something like:

char[][] boardArray = new char[height][width];

EDIT: Okay, now for the printing part. Your current code is:

public void displayBoard(){
    for (int k=0; k < boardArray.length; k++)
           for (int l=0; l < boardArray[k].length; l++){
               System.out.print(boardArray[k][l]);
           }
    System.out.println();
}

This is equivalent to:

public void displayBoard() {
    for (int k = 0; k < boardArray.length; k++) {
        for (int l = 0; l < boardArray[k].length; l++) {
            System.out.print(boardArray[k][l]);
        }
    }
    System.out.println();
}

... so you're only calling println after the outer loop has finished. If you just move the call to println to after the inner loop, it'll be fine:

public void displayBoard() {
    for (int k = 0; k < boardArray.length; k++) {
        for (int l = 0; l < boardArray[k].length; l++) {
            System.out.print(boardArray[k][l]);
        }
        System.out.println();
    }
}

Note that this sort of thing is clearer if you always include braces for loops, if statements etc.

Upvotes: 3

Related Questions