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,

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++){

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()


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()) {
    if (j < rname.size()) {

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: