For loop multiple conditions

I want to check two conditions in one ‘for’ loop.

lname and rname are ArrayLists
Their size is not the same. Say for example,
lname.size()=10
rname.size()=5

so, i want ‘i’ to run from 0 to 9
and ‘j’ to run from 0 to 4

for(i=0,j=0;i<lname.size(), j<rname.size();i++,j++){
System.out.println(lname.get(i));
System.out.println(rname.get(j));
}

Eclipse tells me there’s a syntax error in this for loop. But I cant figure out where it is. Any help or comments is most appreciated.

The condition should use a boolean operator, not a comma:

i < lname.size() && j < rname.size()

Cheers,
D.

ty :slight_smile:

hmm you can use boolean “&&” but in this case this will be false as soon as j equals to 5 so you wont be able iterate all variables in lname.

so either use two seperate loops or


for (i = 0, j = 0; i < lname.size() || j < rname.size(); i++, j++){
    if (i < lname.size()) {
        System.out.println(lname.get(i));
    }
    if (j < rname.size()) {
        System.out.println(rname.get(j));
    }
}

thanks avci84. Yea, the loop was terminating earlier than I wanted it to. Nice fix.

Just my 2 cents.

Yes, the amended code will work, but I think it just highlights why we don’t do things like this.

If your arrays are parallel (2 or more arrays of the same length with corresponding indexes) then something like this works great.

When your arrays are of different length, however, this approach is confusing and inefficient. (10 loops + 20 ifs > 10 loops + 5 loops)

Yea, I am not being very efficient here. Point taken. :slight_smile: