【问题标题】:Need explanation for the output of the following java code以下java代码的输出需要说明
【发布时间】:2016-04-17 05:37:00
【问题描述】:
public class Test {  
  public static void main (String args[]) {
    int i = 0;
    for (i = 0; i < 10; i++);
    System.out.println(i + 4);
  }
}   

下面代码的输出是14,为什么不是4?

怎么可能是 14 岁?需要解释一下

提前谢谢你...

【问题讨论】:

  • 循环将变量 i 设置为 0。10 次迭代后 i 为 10。i + 4 然后为 14!
  • 是什么让你认为结果应该是 4?
  • 您可能会因为行尾的分号以“for”开头而感到困惑。这意味着您定义了一个空循环,它将变量 i 增加了十倍。 System.out.println 只在循环结束后出现一次,此时 i 的值已经是 10。所以输出必须是 14。

标签: java loops for-loop iteration


【解决方案1】:

简单。

  • 循环将i 递增10 而不做任何其他事情(注意for 循环定义后的;
  • System.out 语句在循环外打印i + 4(仅一次),即14

【讨论】:

    【解决方案2】:
    for (i = 0; i < 10; i++);
    

    这个循环除了将i 增加一、十次之外什么都不做。

    然后

    System.out.println(i + 4);
    

    评估为

    System.out.println(10 + 4);
    
    // output
    14 
    

    如果你把for (i = 0; i &lt; 10; i++);末尾的分号去掉,你会得到

    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    

    作为输出。

    【讨论】:

      【解决方案3】:

      见cmets中的描述:

              // Declare variable 'i' of type int and initiate it to 0
              // 'i' value at this point 0;
              int i = 0;
      
              // Take variable 'i' and while it's less then 10 increment it by 1
              // 'i' value after this point 10;
              for (i = 0; i < 10; i++);
      
              // Output to console the result of the above computation
              // 'i' value after this point 14;
              System.out.println(i + 4);
      

      【讨论】:

        【解决方案4】:

        System.out.println(i + 4); 将在 for (i = 0; i &lt; 10; i++); 语句被评估后被评估和执行。

        for (i = 0; i &lt; 10; i++); 的结果将是 10。条件 i &lt; 10 将一直为真,直到第 10 次迭代 i=9 并且在第 11 次迭代中,i 将是 10,因为 i++ 将被计算,这里 i&lt;10 条件失败。现在i 的最终值将是10。 评估下一条语句System.out.println(i + 4);,即i(=10)+4 = 14

        【讨论】:

          猜你喜欢
          • 2012-08-12
          • 1970-01-01
          • 1970-01-01
          • 2017-05-03
          • 2023-03-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多