需要解释以下java代码的输出吗 公共类测试{ 公共静态void main(字符串参数[]){ int i=0; 对于(i=0;i

需要解释以下java代码的输出吗 公共类测试{ 公共静态void main(字符串参数[]){ int i=0; 对于(i=0;i,java,loops,for-loop,iteration,Java,Loops,For Loop,Iteration,下面代码的输出是14。为什么不是4 怎么可能是14岁?需要解释一下吗 提前谢谢你…简单 循环将i增加10,而不做任何其他操作(注意;循环定义的后面的) System.out语句在循环外打印i+4(仅一次),即14 评估为 System.out.println(i + 4); 如果将分号放在(i=0;i

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

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

提前谢谢你…

简单

  • 循环将
    i
    增加
    10
    ,而不做任何其他操作(注意
    循环定义的
    后面的
  • System.out
    语句在循环外打印
    i+4
    (仅一次),即
    14
评估为

System.out.println(i + 4);
如果将分号放在(i=0;i<10;i++)的
末尾,您将获得

System.out.println(10 + 4);

// output
14 

作为输出。

请参见注释中的说明:

4
5
6
7
8
9
10
11
12
13
//声明int类型的变量“i”并将其初始化为0
//此时的“i”值为0;
int i=0;
//取变量“i”,当它小于10时,将它增加1
//第10点之后的“i”值;
对于(i=0;i<10;i++);
//将上述计算结果输出到控制台
//第14点之后的“i”值;
系统输出打印项次(i+4);
系统输出打印LN(i+4)将在(i=0;i<10;i++)的
之后得到计算和执行语句


(i=0;i<10;i++)的
结果将为
10
。条件
i<10
将为真,直到
i=9
,这是第10次迭代,在第11次迭代中
i
10
,因为将计算
i++
,在这里,循环将变量i设置为0。10次迭代之后,我是10。i+4等于14!是什么让您认为结果应该是4?您可能会感到困惑,因为这行末尾有分号,以“for”开头。这意味着您定义了一个空循环,它将变量i增加十倍。当i的值已经为10时,System.out.println仅在循环完成后出现一次。所以输出必须是14。
System.out.println(10 + 4);

// output
14 
4
5
6
7
8
9
10
11
12
13
        // 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);