如果布尔表达式增加int内部

use*_*952 2 java

我想了解如何在每个循环迭代的if(布尔表达式)内增加int x这
怎么可能?它是如何工作的?

  public class MethodsTest {

 public static void main(String[] args) {
    int x= 0;

    for (int z = 0; z < 5; z++) 
    {

        if(x++ > 2){

        }

        System.out.println(x);
    }

}
 }
Run Code Online (Sandbox Code Playgroud)

输出将是
1
2
3
4
5

das*_*ght 6

x++是一个复合赋值算子,相当于评价x = x + 1发生的副作用.因此,该语句相当于一对这样的语句:if

    if(x > 2) {
        x = x + 1;
        // At this point, the side effect has taken place, so x is greater than it was before the "if"
        ...
    } else {
        // The side effect takes place regardless of the condition, hence the "else"
        x = x + 1;
    }
Run Code Online (Sandbox Code Playgroud)

请注意,此代码被强制重复该x = x + 1部分.使用++可以避免这种重复.

有一个预增量对应物x++- 即++x.在这种形式中,赋值在表达式求值之前发生,因此条件变为

if ((x = x + 1) > 2) {
    // Note that the condition above uses an assignment. An assignment is also an expression, with the result equal to
    // the value assigned to the variable. Like all expressions, it can participate in a condition.
}
Run Code Online (Sandbox Code Playgroud)