【问题标题】:For loop Auto increment variableFor循环自动递增变量
【发布时间】:2020-02-10 06:34:53
【问题描述】:

for(int i=0; i < 5; i++) 循环中,i 不是在 printf 读取之前增加了i++ 吗?如果是这样,它应该返回i=1 对吗?这里首先返回0是什么概念。

public class Application {
    public static void main(String[] args) {

        for(int i=0; i < 5; i++) {
            System.out.printf("The value of i is: %d\n", i);
        }
    }
}

【问题讨论】:

    标签: java for-loop


    【解决方案1】:

    不,循环增量是在循环体的末尾计算的。

    【讨论】:

      【解决方案2】:

      14.14.1. The basic for Statement

      BasicForStatement:
          for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
      
      • 如果 Expression 不存在,或者存在且其评估(包括任何可能的拆箱)产生的值为 true,则执行包含的 Statement。然后有一个选择:

        • 如果Statement执行正常完成,则依次执行以下两步:

          • 首先,如果存在 ForUpdate 部分,则表达式按从左到右的顺序计算;它们的值(如果有)将被丢弃。如果任何表达式的求值由于某种原因突然完成,for 语句也会因为同样的原因而突然完成;突然完成的语句右侧的任何 ForUpdate 语句表达式都不会被计算。

          • 其次,执行另一个for迭代步骤。

      在您的示例中,这意味着i++ 将在System.out.printf 行之后执行。

      【讨论】:

        【解决方案3】:

        行为与

        相同
         for(int i=0; i < 5; ) {
                    System.out.printf("The value of i is: %d\n", i);
                   //whatever
        
        
                   //at the very end; just before exiting the loop 
                   i = i + 1;
                   // exit the loop
                }
        

        【讨论】:

          【解决方案4】:

          在 for 循环中,循环仅在 i

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-10-15
            • 2020-06-11
            • 1970-01-01
            • 2017-01-26
            • 2018-12-25
            • 2017-03-22
            • 1970-01-01
            • 2014-09-10
            相关资源
            最近更新 更多