0

I'm trying to get my loop to go through the array 16 times. When I use upCollisions[i], it doesn't work but when I use upCollisions[0] or any other index of the array, it works. I can't understand why it is not working using the for loop.

Here's my code:

public void handleUpArrow()
{
    int upCollisions[] = {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,};
    for(int i =0; i < 16; i++)
    {
        if(goldenBallPosition == upCollisions[i])
        {
        }
        else
        {
            jBGrid[goldenBallPosition].setIcon(imageSand);
            jBGrid[goldenBallPosition -16].setIcon(imageBall);
            goldenBallPosition -= 16;
            jBCompass.setIcon(imageCompassNorth);
            jTDirection.setText("N");
            jTSquare.setText((""+goldenBallPosition));
        }
    }
}
4

1 Answer 1

1

There are some problems with your code. First of all it's better to make the work in the if branch, and not in the else. Then I think the problem could be in this line of code:

goldenBallPosition -=16;

If I do undestand correctly your code, it could help if you use a loop like this

for (int i = 15; i >= 0; i--)

Don't you receive an ArrayOutOfBoundException during execution?

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

2 Comments

How goldenBallPosition is initialized? I think this is the core of the problem.
@Callum At what line does the ArrayIndexOutOfBoundsException occur?

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.