class Foozit {
public static void main(String[] args) {
Integer x = 0;
Integer y = 0;
for (Short z = 0; z < 5; z++) {
if ((++x > 2) || ++y > 2)
x++;
}
System.out.println(x + "Hello World!" + y);
}
}
I tried this scjp piece of code and I am getting the output 5 3 can anyone tell me where i am going wrong
我尝试了这个scjp代码,我得到了输出5 3,谁能告诉我哪里出错了。
1 个解决方案
#1
6
The loop executes 5 times (z from 0 to 4)
循环执行5次(z从0到4)
In the if condition, ++x is evaluated all five times. But ++y is evaluated only when first part of condition is false.
在if条件下,所有5次都对+x进行评估。但是,只有当条件的第一部分为假时,才计算++y。
i.e., This condition:
即。这个条件:
if ((++x > 2) || ++y > 2)
becomes:
就变成:
//1st iteration
if( 1 > 2 || 1 > 2 ) //False, x++ is not evaluated
//2nd iteration
if( 2 > 2 || 2 > 2 ) //False, x++ is not evaluated
//3rd iteration
if( 3 > 2 || 2 > 2 ) //True, the second ++y is skipped, but x++ is evaluated, x becomes 4
//4th iteration
if( 5 > 2 || 2 > 2 ) //True, the second ++y is skipped, but x++ is evaluated, x becomes 6
//5th iteration
if( 7 > 2 || 2 > 2 ) //True, the second ++y is skipped, but x++ is evaluated, x becomes 8
So finally, we have:
最后,我们有:
x = 8 and y = 2
Remember: ++x is pre-increment (think change-and-use) while x++ is post-increment(think use-and-change)
记住:++x是预增量(想想转换和使用),而x++是后增量(想想使用和改变)
#1
6
The loop executes 5 times (z from 0 to 4)
循环执行5次(z从0到4)
In the if condition, ++x is evaluated all five times. But ++y is evaluated only when first part of condition is false.
在if条件下,所有5次都对+x进行评估。但是,只有当条件的第一部分为假时,才计算++y。
i.e., This condition:
即。这个条件:
if ((++x > 2) || ++y > 2)
becomes:
就变成:
//1st iteration
if( 1 > 2 || 1 > 2 ) //False, x++ is not evaluated
//2nd iteration
if( 2 > 2 || 2 > 2 ) //False, x++ is not evaluated
//3rd iteration
if( 3 > 2 || 2 > 2 ) //True, the second ++y is skipped, but x++ is evaluated, x becomes 4
//4th iteration
if( 5 > 2 || 2 > 2 ) //True, the second ++y is skipped, but x++ is evaluated, x becomes 6
//5th iteration
if( 7 > 2 || 2 > 2 ) //True, the second ++y is skipped, but x++ is evaluated, x becomes 8
So finally, we have:
最后,我们有:
x = 8 and y = 2
Remember: ++x is pre-increment (think change-and-use) while x++ is post-increment(think use-and-change)
记住:++x是预增量(想想转换和使用),而x++是后增量(想想使用和改变)