1
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 谁能告诉我哪里出错了

4

1 回答 1

6

循环执行 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++ 是后增量(考虑使用和更改)

于 2012-07-11T13:31:22.050 回答