How does a for loop check its conditions in Java?

前端 未结 5 1833
小鲜肉
小鲜肉 2021-01-04 19:32

My question has to do with the order in which java checks the conditions of a for loop when there is a print statement in the \"conditions\" of the loop. It

5条回答
  •  情书的邮戳
    2021-01-04 20:07

    for (int i = -1; i < n; System.out.print(i + " ")) 
    {
        i++;
    }
    

    First, i is initialized to-1 (only happens once), and i < n, so we go into the loop. i is incremented inside of the for loop, so now i == 0. We then go to the print statement. Repeat.

    The expected behavior that you want would require something like:

    for (int i = -1; i < n; i++) 
    {
        System.out.print(i + " ")
    }
    

    Here's a reference for the for statement.

提交回复
热议问题