gpt4 book ai didi

java - SCJP程序给出输出8 2怎么办?

转载 作者:行者123 更新时间:2023-11-29 07:13:52 25 4
gpt4 key购买 nike

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

我尝试了这段 scjp 代码,得到的输出是 5 3 谁能告诉我哪里出错了

最佳答案

循环执行5次(z从0到4)

在 if 条件下,++x 被计算了五次。但是只有当条件的第一部分为假时,++y 才会被评估。

即,这种情况:

if ((++x > 2) || ++y > 2)

变成:

//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

最后,我们有:

x = 8 and y = 2

记住:++x 是预递增(想想改变和使用)而 x++ 是后递增(想想使用和改变)

关于java - SCJP程序给出输出8 2怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11433516/

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