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
  • 2
    Please show a short but complete program that demonstrates the problem - explaining exactly what you mean by "it doesn't work". Commented Mar 4, 2015 at 20:21
  • Remove the last comma in the array. There is one too many at the end. Commented Mar 4, 2015 at 20:22
  • You should put the if condition as a NOT condition and then put the code within that if instead of having an empty if and the code in the else. It will have the same effect and be much cleaner Commented Mar 4, 2015 at 20:45
  • Also where is goldenBallPosition being initialized? Commented Mar 4, 2015 at 20:48

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.