coretechie
coretechie

Reputation: 1218

Why is i++ looping twice here?

When below code executes i=0, j=0 and length = 9 and loops = 3

Surprisingly with each line, i increased by 2 rather than 1.

Can you tell why?

        String arr[] = stringToSplit.split(delimiter);
        int length = arr.length;
        int loops = length/4+length%4;
        for(int i=0,j=0; j<loops && i<length; j++){
            DummyClass dummyClass= new DummyClass ();
            MyHelper.addInMappedElement(i<length?arr[i++]:null, value1, dummyClass) ;
            MyHelper.addInMappedElement(i<length?arr[i++]:null, value2, dummyClass) ;
            MyHelper.addInMappedElement(i<length?arr[i++]:null, value3, dummyClass) ;
            MyHelper.addInMappedElement(i<length?arr[i++]:null, value4, dummyClass) ;
        }

Note: I am aware that i should be incrementing 4 times after completing one loop but that is not the case here. For eg : if the array is [Value1 , value2 , value 3 , value 4, Value5 , value12 , value q3 , value w4, val5]

What I get mapped in my final result is just value 3 ,Value5, value q3 and val5.

Do you get my question now?

Upvotes: 0

Views: 119

Answers (3)

coretechie
coretechie

Reputation: 1218

Got the fix :

 for(int i=0,j=0; j<loops && i<length; j++){
        DummyClass dummyClass= new DummyClass ();
        MyHelper.addInMappedElement(i<length?arr[i++].toString():null, value1, dummyClass) ;
        MyHelper.addInMappedElement(i<length?arr[i++].toString():null, value2, dummyClass) ;
        MyHelper.addInMappedElement(i<length?arr[i++].toString():null, value3, dummyClass) ;
        MyHelper.addInMappedElement(i<length?arr[i++].toString():null, value4, dummyClass) ;
    }

B-)

Upvotes: 0

Maroun
Maroun

Reputation: 95998

i++ is the same as:

int temp = i;
i = i + 1;   ← i is actually changed ¯\_(ツ)_/¯
return temp;

i is incremented 4 times in your code.

Upvotes: 1

Eran
Eran

Reputation: 393986

You have 4 i++ statements in each iteration, so it's actually incremented up to 4 times (as long as i<length).

Upvotes: 3

Related Questions