1

I have a piece of code:

public void setBoardMemberPosition() {

    int[] position = null;

    do{
        positionX = RandomNumberGenerator.generateRandomNumber(Board.DIMENSION);
        positionY = RandomNumberGenerator.generateRandomNumber(Board.DIMENSION);

        position = new int[] { positionX, positionY };


    } while(checkIfPositionIsOccupied(position));

    board.setElementAt(positionX, positionY, name);
    storedMembers.add(position);

}

Can someone explain to me why the elements are not being added to the list, where:

private ArrayList<int[]> storedMembers = new ArrayList<int[]>();is a Class variable and:checkIfPositionIsOccupied(position) returns true/false

if (storedMembers.contains(position))

i have a feeling its something to do with the do while, ive debugged it with no luck.

2 Answers 2

2

If you want to add the array position to the ArrayList on each iteration, your add() call must be inside the loop:

do {
    // ...

    storedMembers.add(position);
} while(...);

Edit:

for (int i = 0; i < storedMembers.size(); i ++)
    // ...

    if (!checkIfPositionIsOccupied(position))
        storedMembers.add(position);
}
Sign up to request clarification or add additional context in comments.

6 Comments

But i dont need it to be on each itteration, just if checkIfPositionIsOccupied(position) returns false. thats why i initalised the variable before the loop??
Then you can add a condition inside the loop. The check checkIfPositionIsOccupied(position) shouldn't be loop condition. But you will have to think how many iterations there would be?
so i should probably use a for loop of storedMembers.size() itterations?
Yes, in that case a for loop will be better. See edit.
Ok ill try it that way, but it still dosent clear up the original problem... im not understanding it atall, ive even tried adding it to the list int the checkIfPositionIsOccupied(position) method with no luck...
|
0

Because you don't add in your while loop anything to the list?!

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.