Search code examples
javafor-loopincrementterminationdecrement

Different increment on a for loop depending on a boolean


How can i select the increment on a for loop depending on a boolean,i am trying to do something like this:

    for (int y = iniY; isdown? (y >= endY): (y <= iniY+dy) ; isdown? --y:y++);

the for loop accepts the termination but not the increment...

The working code i currently have is something like this:

    if(isdown)
        for (int y = iniY; y >= endY; --y) {
            code lines...
        }
    else
        for (int y = iniY; y <= iniY+dy; ++y) {
            code lines...
        }

the code can not be extracted to a new method because it works on many variables...


Solution

  • Similar to minitech's solution but without a branch inside the loop.

    int end = isdown ? iniY - endY : dy;
    int direction = isdown ? -1 : +1;
    
    for(int i = 0; i <= end; i++) {
        int y = iniY + direction * i;
        …
    }