gpt4 book ai didi

java - 在 if boolean 表达式中递增 int

转载 作者:行者123 更新时间:2023-12-02 09:14:51 26 4
gpt4 key购买 nike

我想了解如何在每次循环迭代的 if ( boolean 表达式)内递增 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);
}

}
}

输出将是
1
2
3
4
5

最佳答案

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;
}

请注意,此代码被迫重复 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.
}

关于java - 在 if boolean 表达式中递增 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20916172/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com