Joeblackdev
Joeblackdev

Reputation: 7327

For loop not evaluating

I can't figure this out. I have the following code:

import java.util.ArrayList;
import java.util.List;


public class TestLoop {
    public static List<String> strArray = new ArrayList<String>();

    static {
        strArray.add("Some");
        strArray.add("Silly");
        strArray.add("String");
    }

    public static void main(String[] args) {
        int doNotPrintIndex = 1;
        int beginIndex = doNotPrintIndex == 0 ? 1 : 0;
        for (int i = beginIndex; i < strArray.size() && i != doNotPrintIndex; i++) {
            System.out.println(strArray.get(i));
        }
    }

}

Essentially, if I have an ArrayList, I never want to print out what is stored at index 'doNotPrintIndex' within the ArrayList. However, in the following case, the loop only executes once. Is there something wrong in my logic?

Upvotes: 1

Views: 95

Answers (4)

ArVan
ArVan

Reputation: 4275

Well, it should loop once :) You see, in a your for loop works like this: it checks the conditions 1 and 2: i=0, i<x && i!=1 and if this condition is true, it steps inside the for loop braces. After finishing woth operations there, it comes back and changes i: i++. So when your i==1, the condition 2 is false, and the loop is over. It's like you have for(i=0; i<3; i++) {...} and after last increment i equals 3. The condition i<3 is false, so the loop is finished.

Upvotes: 0

Rick Goldstein
Rick Goldstein

Reputation: 299

The conditional in the for loop indicates when the loop should stop. You should put the test for doNotPrintIndex into the body of the loop.

Upvotes: 1

Jon Lin
Jon Lin

Reputation: 143906

Because beginIndex is 0 and doNotPrintIndex is 1, so after 1 iteration, i == doNotPrintIndex and the loop stops. You need to remove that from the for loop and make it an if statement inside the loop:

    for (int i = beginIndex; i < strArray.size(); i++) {
        if(i != doNotPrintIndex)
            System.out.println(strArray.get(i));
    }

Upvotes: 2

Ted Hopp
Ted Hopp

Reputation: 234847

Your loop is exiting as soon as i hits doNotPrintIndex. Try this loop:

for (int i = beginIndex; i < strArray.size(); i++) {
    if (i != doNotPrintIndex) {
         System.out.println(strArray.get(i));
    }
}

Alternatively, you could have two loops one after another:

for (int i = beginIndex; i < doNotPrintIndex; i++) {
     System.out.println(strArray.get(i));
}

for (int i = doNotPrintIndex + 1; i < strArray.size(); i++) {
     System.out.println(strArray.get(i));
}

Upvotes: 5

Related Questions