0

Alright so basically, I have a multi-dimensional array, Board[8][8]. I'm trying to take random values within the array and make them a different value. The value that I am changing must already be a certain value. The code I am running keeps yeilding these results:

java.lang.ArrayIndexOutOfBoundsException: 8
       at checkers.init(checkers.java:32)
       at sun.applet.AppletPanel.run(Unknown Source)
       at java.lang.Thread.run(Unknown Source)

This is the code causing the problem. Note that line 8 is a variable declaration:

int BLACK = 1;

    Random generator = new Random();
    int checkersCount_B = 0, checkersCount_W = 0, x, y;

    while(checkersCount_B < 9){
        x = generator.nextInt(9);
        y = generator.nextInt(9);

        if(Board[x][y] == BLACK){
            Board[x][y] = BLACK_CHECKER;
        //  System.out.println(x + " " + y);
            checkersCount_B ++;
        } else{
            //nothing
        }
    }

Line 32 is the if statement.

The code works for a couple runs through the while loop, but never makes past two or three, any suggestions?

1

6 Answers 6

4

The indexes of your array go from 0 to 7. Iterating while (index<9), will take the 9th element (given by index 8).

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

1 Comment

Thanks, it's one of those days... you just saved me hours
1

You will run off the end of one of the arrays, because eventually nextInt will return 8, but the indexes of your arrays are 0-7 (length 8).

Use generator.nextInt(8) to return a random number between 0 and 7.

Comments

0

You are generating numbers from 0 to 8 with your generator.nextInt(9). Since the board's width and height are 8, you should generate indexes that range from 0 to 7. Change the 9 to 8 in your nextInt call.

Comments

0

In arrays indexes start from 0 (not 1) so for array of 8 elements you will have to use indexes from 0 to 7.

Comments

0

Indices go from 0 to 7; thus, you must generate a value within that range. The length, however, is 8.

Comments

0

Copy-and-pasteable solution:

Random generator = new Random();
int checkersCount_B = 0, checkersCount_W = 0, x, y;

while(checkersCount_B < 8){
    x = generator.nextInt(8);
    y = generator.nextInt(8);

    if(Board[x][y] == BLACK){
        Board[x][y] = BLACK_CHECKER;
    //  System.out.println(x + " " + y);
        checkersCount_B ++;
    } else{
        //nothing
    }
}

Comments

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.