I can not understand how this code works. Explain on the fingers, please.

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

Displays:

  // Yuhu // Tata // Yuhu // Yuhu // 3 
  • I understand that Yuhu Tata is immediately taken out, but how does he go on to output Yuhu twice? - GPIE

3 answers 3

 int i; //цикл (выполняется 5 раз: i тут от 0 до 4) for (i = 0; i < 5; i++) { //если шаг цикла больше или равен 3-м, то тогда цикл перестает выполняться //break - `ломает` цикл if (i >= 3) { break; } System.out.println("Yuhu"); //если шаг цикла больше или равен 1, то тогда мы переходим к началу цикла //оператор continue возвращает цикл к началу выполнения if (i >= 1) { continue; } System.out.println("Tata"); } System.out.println(i); 

Here's how the compiler will do this (schematically):

 0 шаг: i = 0 i >= 3 //не выполнится System.out.println("Yuhu"); i >= 1 //не выполнится System.out.println("Tata"); 1 шаг: i = 1 i >= 3 //не выполнится System.out.println("Yuhu"); i >= 1 { continue; } //выполнится //переходим к началу цикла и пропускаем оставшееся тело цикла 2 шаг: i = 2 i >= 3 //не выполнится System.out.println("Yuhu"); i >= 1 { continue; } //выполнится //переходим к началу цикла и пропускаем оставшееся тело цикла 3 шаг: i = 3 i >= 3 { break; } //выполнится //цикл остановится 

Well, in the end we output to the console i , which is equal to the 3rd.

    1. During the first iteration, neither of the conditions is true and both words are output.
    2. In the second and third iterations, the second condition is true and the second word is not output, because the loop immediately goes to the next iteration.
    3. At 4 iterations, the first condition is true, the cycle ends and the value i is printed after the cycle

      Because there is a condition

       if (i >= 1) { continue; } 

      If i> = 1, then everything that goes on is skipped and the next iteration starts. Therefore, System.out.println("Tata"); done only 1 time.