简体   繁体   中英

While loop stop at first false condition

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 while loop will stop at the first false evaluation 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?

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.

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--;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM