Codegym University コースの一部としてのメンターによる講義の抜粋。フルコースにお申し込みください。


"やあ。"

「こんにちは、エリー!」

「ループについて学習しましょう。ループは if/else ステートメントと同じくらい単純ですが、さらに興味深いものです。ループを使用すると、任意のコマンドまたはコマンドのブロックを複数回実行できます。一般に、ループは次のようになります。」

ループ(例1)
while(boolean condition)
    command;
ループ(例2)
while(boolean condition)
    block of commands in curly brackets

「すべて非常に単純です。ループ条件が true である限り、コマンドまたはブロックが何度も実行されます。最初に条件がチェックされます。条件が true の場合、ループ本体 (コマンドのブロック) が実行されます。条件が再度チェックされます。条件が true の場合、ループ本体が再度実行されます。条件が true でなくなるまで、これが繰り返されます。

「それが常に真である場合、または常に偽である場合はどうなりますか?」

「常に true の場合、プログラムは実行を停止することはありません。ループを無限に繰り返します。常に false の場合、ループ本体は決して実行されません。」

ここではいくつかの例を示します。

Javaコード 説明
int i = 3;
while (i >= 0)
{
    System.out.println(i);
    i--;    //Decrease by 1
}
3
2
1
0
int i = 0;
while (i < 3)
{
    System.out.println(i);
    i++;   //Increase by 1
}
0
1
2
boolean isExit = false;
while (!isExit)
{
    String s = buffer.readLine();
    isExit = s.equals("exit");
}
プログラムは、文字列「exit」が入力されるまで、キーボードからの文字列を出力します。
while (true)
    System.out.println("C");
プログラムは画面上に文字Cを繰り返し表示します。
while (true)
{
    String s = buffer.readLine();
    if (s.equals("exit"))
        break;
}
プログラムは、文字列「exit」が入力されるまで、キーボードから文字列を読み取ります。
2
タスク
Java Syntax,  レベル 4レッスン 8
ロック未解除
Code entry
Your attention, please! Now recruiting code entry personnel for CodeGym. So turn up your focus, let your fingers relax, read the code, and then... type it into the appropriate box. Code entry is far from a useless exercise, though it might seem so at first glance: it allows a beginner to get used to and remember syntax (modern IDEs seldom make this possible).

「条件文の後で、これは複雑ではないようです。すでに試してみたいと思っています。」