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 が 5 回すべて評価されます。ただし、++y は、条件の最初の部分が false の場合にのみ評価されます。

つまり、この条件:

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 に答える