后/增量混乱

时间:2016-03-22 05:10:46

标签: java post-increment pre-increment unary-operator

根据我的理解,如果我有变量k = 5,我做++ k,k = 6的新值。如果我做k ++,则值保持为5,直到k出现在程序中第二次,当它变为6时。例如:

k = 5;
System.out.println(k++); //prints 5, but now that k has appeared the second time, its value is incremented to 6
System.out.println(k); //prints 6

但是,在此代码中:

class test {
    public static void main(String args[]){
        for(int i =0; i<10; i++){
            System.out.println(i);
        }
        int x = 0;
        x++;
        System.out.println(x);
    }
}

输出:

0
1
2
3
4
5
6
7
8
9
1

在循环中,虽然变量i第二次出现(在System.out.println(i)中),但它的值保持为0.但对于x,它第二次出现时(在System.out中) .println(x);)其值递增。 为什么?我对后期和预增量工作感到困惑。

1 个答案:

答案 0 :(得分:1)

代码

    for(int i =0; i<10; i++){
        System.out.println(i);
    }

首先将变量i初始化为0,然后检查它是否满足条件i&lt; 10并打印变量并最后增加变量i。

这就是for循环的工作原理。

在你编写的第二段代码中,它递增变量x并最后打印x的值。

相关问题