[Solved]ArrayOutOfBoundsException help.

Before you say anything, I have googled this problem.

I’m getting an ArrayIndexOutOfBoundException every time my


int pX;

gets to 14/15. I do not understand why, because technically the


int[][] tileID = new int[15][20];

and the pX should refer to the 20. I do not know how to approach this problem, this is my code for moving my player, it includes a check to see if the player is on a tile it shouldn’t be on, which i believe is where the problem is coming from.


public void movePlayer(int pSX, int pSY)
	{
		// Set the previous positions of the x, y coordinates
		prevX = pX;
		prevY = pY;
		
		// Set The Player Speed
		pSpeedX = pSX;
		pSpeedY = pSY;
		
		// Move player then check if they are on a tile
		if( pSY == 0)
		{
				pX += pSpeedX;
				if( tiles.tileID[pY][pX] == 1)
				{
					pX = prevX;
					pY = prevY;
				}
		}
		if( pSX == 0)
		{
				pY += pSpeedY;
				if( tiles.tileID[pY][pX] == 1)
				{
					pX = prevX;
					pY= prevY;
				}
		}
	}

I know I’m posting a lot, but I’m really not sure how to do these things :confused:

Will pSX only be equal to 1,0, or -1?

If not, that would explain why it’s going out of bounds. Basically you need to ensure that pX and pY aren’t greater than the length of your array-1 since arrays start with 0.

-Pickle:)

Such exceptions always have a line number associated with them. Put a breakpoint on that line and execute that program using a debugger. Look at your local variables and ask “What is the max index of the array? What value am I trying to use? How did the program get to this state?”

I got it sorted, don’t know how but it works, and its been tested a lot so it should be good.

If you don’t know how it works than it’s not good, if you don’t understand your code you’ll have no way to debug it and you’ll continually ask questions on forums like this…

the players pX was the equal to the [20] part of tileID[15][20], so i added an extra column to it, so its tileID[15][21].

I understand it now, the pX wasn’t equal to tileID[y].length - 1 it was equal to tileID[y].length.

i’ve got a little engine set up now, so it’s speeding up my game, all i need to do is create the levels using matrices which means its speeding up the production of it. It’s for blackberry smartphones so it doesn’t have to be amazing :slight_smile: just really good