当条件小于(<)4时,输出如何达到4?

How the output is upto 4 when there is a condition is less than(<)4?

我的输出与 4 个原因一起出现

public class whileProgram {
public static void main(String[] args) {
    int counter = 0;
    while(counter<4){
        counter = counter+1;
        System.out.println(counter);
    }
}

}

    Output:
    1 2 3 4

我认为其他答案并没有完全解释 'why'。这是我对这部分问题的尝试。

考虑代码:

while(counter<4){
    counter = counter+1;
    System.out.println(counter);
}

我们从counter等于0开始,0小于4,所以进入循环体。这里我们首先将计数器递增到 1,然后打印它。所以我们打印 1.

现在我们再来一次。 1小于4,所以我们进入循环体,递增到2,打印2。

现在我们再来一次。 2小于4,所以我们进入循环体,递增到3,打印3。

下一次是 'why' 问题的重点。计数器现在是 3,我们处于 re-evaluating 'while' 条件。 3小于4,所以我们进入循环体。我们将计数器增加到 4。然后我们执行 print 语句,所以打印 4。这就是解释。

理解这一点的关键是语句的顺序执行。你需要像我在这个回答中所做的那样在精神上关注执行。