using continue in a for loop: the order it produces

can someone explain the order of operations for this function, i can not understand the order it is producing:

    // output
    // Yuhu
    // Tata
    // Yuhu
    // Yuhu
    // 3

public class Main {
public static void main(String[] args) {
    int i;
    for (i = 0; i < 5; i++) {
        if (i >= 3) {
            break;
        }
        System.out.println("Yuhu");
        if (i >= 1) {
            continue;
        }
        System.out.println("Tata");
    }
    System.out.println(i);

  }
}

why is it not Yuhu, Tata, Yuhu, Tata, 3?

Answers


First iteration: i is 0: i >= 3 is false, so no break. "Yuhu" is printed. i >= 1 is false, so no continue. "Tata" is printed.

Second iteration: i is 1: i >= 3 is false, so no break. "Yuhu" is printed. i >= 1 is true, so continue ends this iteration only. "Tata" is not printed.

Third iteration: i is 2: i >= 3 is false, so no break. "Yuhu" is printed. i >= 1 is true, so continue ends this iteration only. "Tata" is not printed.

Fourth iteration: i is 3: i >= 3 is true, so break breaks out of the for loop, and the output statement after the for loop prints 3.


because it wont get to "Tata" more than once, it only gets there when i=0, continue immediately begins the next iteration of the loop


Try adding more debug statements to figure it out...

int i;
for (i = 0; i < 5; i++) {
    if (i >= 3) {
        System.out.printf("breaking (i=%d)%n", i);
        break;
    }
    System.out.printf("Yuhu (i=%d)%n", i);
    if (i >= 1) {
        System.out.printf("continuing (i=%d)%n", i);
        continue;
    }
    System.out.printf("Tata (i=%d)%n", i);
}
System.out.println(i);

Prints:

Yuhu (i=0)
Tata (i=0)
Yuhu (i=1)
continuing (i=1)
Yuhu (i=2)
continuing (i=2)
breaking (i=3)
3

Need Your Help

Getting Read time out when connecting to hive/spark sql through squirrel sql

jdbc apache-spark-sql squirrel-sql

I'm trying to use Squirrel SQL to connect to spark-sql thriftserver using jdbc.

URLEncoding a string with Objective-C

objective-c cocoa string urlencode

I'm trying to URL encode a string to form a GET request from objective-c.