Reputation: 41
I don't know why I am incorrect in my bounds and why this error is thrown.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
private int gridSize = 3;
private Point currentStep = new Point(0, 0);
private Point firstStep = new Point(0, 0);
private Point lastStep = new Point(gridSize, gridSize);
private int pedometer = 0;
private int random;
private int down = 0;
private int right = 0;
private byte bottomReached = 0;
private byte rightReached = 0;
private int[][] clearPath2D;
public void createWalk2D() {
clearPath2D = new int[gridSize][gridSize];
for (currentStep = firstStep; currentStep != lastStep; pedometer++) {
step2D();
if (rightReached == 1 && bottomReached == 1) {
break;
}
}
clearField();
}
public void step2D() {
random = stepRand.nextInt();
// add a new step to the current path
currentStep.setLocation(right , down);
clearPath2D[right][down] = 4;
// calculates the next step based on random numbers and weather a side
// is being touched
if (currentStep.x == gridSize) {
rightReached = 1;
random = 1;
}
if (currentStep.y == gridSize) {
bottomReached = 1;
random = 0;
}
// decides the direction of the next step
if (random >= 0.5 && bottomReached == 0) {
down++;
} else if (random < 0.5 && rightReached == 0) {
right++;
} else if (rightReached == 1 && bottomReached == 1) {
done = true;
}
}
so I call the createWalk2D(); then I get the error and eclipse points me to this line of code:
clearPath2D[right][down] = 4;
I assume this is because I am looping incorreclty. I have not been able to find a solution and have googled for about an hour three different days.
this isn't all the code but this is the part that I think is throwing it off. Thank you in advance for any help with the error. If you need the whole code please let me know.
EDIT: Nevermind I figured it out.
I had to add 1 to the initial declaration of the array
in this case it meant changing
clearPath2D = new int[gridSize][gridSize];
to
clearPath2D = new int[gridSize + 1][gridSize + 1];
Upvotes: 1
Views: 54
Reputation: 67019
Your immediate problem is in this section of code:
if (currentStep.x == gridSize) {
rightReached = 1;
random = 1;
}
if (currentStep.y == gridSize) {
bottomReached = 1;
random = 0;
}
You should be testing against gridSize-1
, since that is the maximum valid index. As in:
if (currentStep.x == gridSize-1) {
rightReached = 1;
random = 1;
}
if (currentStep.y == gridSize-1) {
bottomReached = 1;
random = 0;
}
Upvotes: 1