1

I have this while loop:

//All of this code is inside a for loop
positionUp = i - 1;

while ((positionUp > 0) && boardMatrix[positionUp][j] == boardMatrix[i][j]) {

    //do something

    positionUp--;
}

At some point, it is possible that positionUp it's assigned with the value -1 (when i=0)

I thought that the whileloop will stop at the first falseevaluation thus not evaluating boardMatrix[positionUp][j] and not getting java.lang.ArrayIndexOutOfBoundsException: -1

I'm not seeing how can I solve this. Can someone point me in the way?

Favolas
  • 6,963
  • 29
  • 75
  • 127

3 Answers3

8

Change your loop (temporarily) to:

System.out.println ("pos="+positionUp+",i="+i+",j="+j);
while ((positionUp > 0) && boardMatrix[positionUp][j] == boardMatrix[i][j]) {
    positionUp--;
    System.out.println ("pos="+positionUp+",i="+i+",j="+j);
}

to see which variable is causing the problem. The Java logical operators do short-circuit so the problem most likely lies with the other variables, depending on how they change in the loop.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Thanks. Problem was with the `j` variable BEFORE entering the while loop. I've checked Only inside the while loop. Thanks – Favolas May 08 '13 at 11:43
0

your problem is: the while loop trys to resolve your condition. your condition contains an access to a array-index which not exists. so before your condition turns "false", an ArrayOutOfBoundsException is thrown.

to solve this you could go:

while ((positionUp > 0) && 
       null != boardMatrix &&
       null != boardMatrix[positionUp][j] && 
       null != boardMatrix[i][j] && 
       boardMatrix[positionUp][j] == boardMatrix[i][j]) {

    //do something

    positionUp--;
}
desperateCoder
  • 700
  • 8
  • 18
  • That will _still_ raise an exception by the way since you're still indexing an invalid position and _then_ comparing it to null for some reason. – paxdiablo May 09 '13 at 00:39
0

Java does have short-circuit operators (&& and || - see Java logical operator short-circuiting). So as long as positionUp is <= 0, the second part will not execute.

This strongly suggests the ArrayOutOfBoundsException originates in your i and j variables.

I would output them (before they are used in the array) so you can see what values they have when the exception is thrown.

Community
  • 1
  • 1
matt freake
  • 4,877
  • 4
  • 27
  • 56