Kosjfn Sdgn
Kosjfn Sdgn

Reputation: 1

Changing values in a 2D array

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?

Upvotes: 0

Views: 103

Answers (6)

Aaron_H
Aaron_H

Reputation: 1683

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
    }
}

Upvotes: 0

Franklin
Franklin

Reputation: 1801

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

Upvotes: 0

rgettman
rgettman

Reputation: 178253

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.

Upvotes: 1

user1697575
user1697575

Reputation: 2848

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

Upvotes: 0

Mohammed Hossain
Mohammed Hossain

Reputation: 1319

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.

Upvotes: 0

Jean Waghetti
Jean Waghetti

Reputation: 4727

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

Upvotes: 4

Related Questions