1

Why does the following code execute six times? Please help me to understand how this works, as I've tried to get it into my head without success.

I thought it would first execute the code once, then increase count to 1, execute it a second time, increase count to 2, execute it a third time, increase count to 3, execute it a fourth time, increase count to 4, execute it a fifth time, increase count to 5, and then stop. Which means it will have executed the loop five times (for the first time, then for when count is 1, 2, 3, 4).

int count = 0;

    do {

        System.out.println("Welcome to Java!");

    } while (count++ < 5);
4

4 に答える 4

2

このコードを実行してみましたか?

int count = 0;

do {

    System.out.println("Welcome to Java! " + count);

} while (count++ < 5);

出力:

Welcome to Java! 0
Welcome to Java! 1
Welcome to Java! 2
Welcome to Java! 3
Welcome to Java! 4
Welcome to Java! 5

これは、何が起こっているのかを理解するのに役立ちます。ポストインクリメント演算子がどのように機能するかについて、あなたの混乱が最も可能性が高いと他の人が言っています。

プリインクリメント演算子とポストインクリメント演算子を理解するために、別のコード サンプルを実行してみましょう

int a = 0;
int b = 0;
System.out.println("pre increment "+ ++a);
System.out.println("post increment "+ b++);

出力:

pre increment 1
post increment 0

要約: ポスト インクリメントでは、変数がインクリメントされる前に式が評価されます。プレ インクリメントでは、変数がインクリメントされた後に式が評価されます。

于 2011-12-29T17:31:34.697 に答える
1

これは、ポストインクリメントを使用しているためです。while条件は最初に (インクリメントの BEFORE からの値で) 評価され、次にcountインクリメントされます。count

試してください++count(最初にインクリメントしてから値を返します)。

編集:

で使用しますが、

for(int i = 0; i < n; i++) {}

大丈夫です(通常は最適化されます)、

for(int i = 0; i < n; ++i) {}

セマンティックの観点から見ると、IMO の方が少し優れています。

演算子のオーバーロードを伴う言語では、さらに複雑になります。i++ は ++i とは異なる副作用を持つ可能性があります。

于 2011-12-29T17:19:48.133 に答える
1

その後置演算子なので、最初に式全体を評価してからインクリメントします

制御はこのように流れます

0
Welcome to Java!
//condition check : 0 then 1
Welcome to Java!
//condition check : 1 then 2
Welcome to Java!
//condition check : 2 then 3
Welcome to Java!
//condition check : 3 then 4
Welcome to Java!
//condition check : 4 then 5
Welcome to Java!
//condition check : 5 then 6
于 2011-12-29T17:17:04.463 に答える
0
count++; // <-- would execute the above code 6 times

ポストインクリメントであり、

++count; // <-- would execute the above code 5 times 

プレインクリメントです

検討:

while (count++ < 5) System.out.println(count); // prints 1 2 3 4 5
while (++count < 5) System.out.println(count); // prints 1 2 3 4

したがって、do...while最初に比較なしで実行し(doのため)、次に比較を実行します。

プレインクリメントの場合、次のように書き直すことができます。

int count = 0;
do {
    // print
    count = count + 1;
} while (count < 5)

ポストインクリメントの場合、次のように書き直すことができます。

int count = 0;
while (count < 5) {
     // print statement
     count = count + 1;
}
于 2011-12-29T17:19:17.367 に答える