私たちの最初のプログラムは、次々に実行される一連の命令でした。フォークはありません。これには、挨拶を表示する HelloWorld が含まれます。算術計算も含まれます。最初のプログラムの後、私たちは分岐する方法、つまり特定の条件に応じてプログラムに異なるアクションを実行させる方法を学びました。セントラルヒーティングと空調システムを制御するコードは次のとおりです。
続く。
if (tempRoom>tempComfort)
airConditionerOn();
if (tempRoom<tempComfort)
heaterOn();
次のステップに進みましょう。日常生活の中で、私たちは、たとえば、パイを作るためにリンゴの皮をむくなど、均一な反復動作を行うことがよくあります。この興味深いプロセスは次のように説明できます。
-
ボウルの中にリンゴがある場合は、ステップ 1.1 から 1.4 を実行します。
- 1.1. リンゴを掴む
- 1.2. 皮をむいてスライスします
- 1.3. リンゴのスライスをパイ生地の中に並べてフライパンに並べる
- 1.4. 手順 1 に戻ります。
- 私たちはリンゴの数に縛られていますが、リンゴの数が十分でない場合、一部のコマンドは「ペイロード」なしで実行されます (そして、存在しないリンゴの皮をむこうとして身を切る可能性があります)。
- 皮をむくコマンドよりも多くのリンゴがある場合、一部のリンゴは皮をむかずに残ります。
- このようなコードは読みにくいです。繰り返しが多く、修正が困難です。
ループとは、アクションを繰り返し実行できるようにするステートメントです
この場合、Java のwhileループはうまく機能します。この構造では、複数のアクションを簡潔でわかりやすい構造にまとめます。Java では、 whileループを使用してパイのリンゴをスライスするアルゴリズムは次のようになります。
while (numberOfApplesInBowl > 0) {
apple = bowl.grabNextApple();
arrangeInPie(apple.peel().slice());
numberOfApplesInBow--; // "--" is the decrement operator, which reduces the number of apples by one
}
System.out.println("The apples for the pie have been processed.");
コマンド構文
whileステートメントの最初の変形は次のようになります。
while (Boolean expression) {
// Loop body — the statement(s) that are repeatedly executed
}
このコードが実行されると何が起こるかを段階的に説明します。
- whileキーワードの後の括弧内にあるブール式を評価します。
- ブール式が true と評価されると、ループ本体内のステートメントが実行されます。ループ本体の最後のステートメントが実行された後、ステップ 1 に進みます。
- ブール式が false と評価された場合は、whileループ後の最初のステートメントにジャンプします。
前提条件付きのループ
ループ本体を実行する前に常にブール式 (ループに入る条件) を評価するため、この形式のwhileループは、前提条件付きループと呼ばれることがよくあります。数値の最初の 10 乗の表を作成してみましょう。
public static void main(String[] args) {
int base = 3; // The number that will be exponentiated
int result = 1; // The result of exponentiation
int exponent = 1; // The initial exponent
while (exponent <= 10) { // The condition for entering the loop
result = result * base;
System.out.println(base + " raised to the power of " + exponent + " = " + result);
exponent++;
}
}
コンソール出力:
3 raised to the power of 1 = 3
3 raised to the power of 2 = 9
3 raised to the power of 3 = 27
3 raised to the power of 4 = 81
3 raised to the power of 5 = 243
3 raised to the power of 6 = 729
3 raised to the power of 7 = 2187
3 raised to the power of 8 = 6561
3 raised to the power of 9 = 19683
3 raised to the power of 10 = 59049
Process finished with exit code 0
事後条件付きのループ
このループの 2 番目のバリエーションを次に示します。
do {
// Loop body — the statement(s) that are repeatedly executed
} while (Boolean expression);
このコードが実行されると何が起こるかを説明します。
- ループ本体が実行されます ( doキーワードの直後)。
- whileキーワードの後の括弧内にあるブール式を評価します。
- ブール式が true と評価された場合は、ステップ 1 に進みます。
- ブール式が false と評価された場合は、whileループ後の最初のステートメントにジャンプします。
public static void main(String[] args) {
int base = 3; // The number that will be exponentiated
int result = base; // The result of exponentiation
int exponent = 1; // The initial exponent
do {
System.out.println(base + " raised to the power of " + exponent + " = " + result);
exponent++;
result = result * base;
} while (result < 10000); // The condition for exiting the loop
}
コンソール出力:
3 raised to the power of 1 = 3
3 raised to the power of 2 = 9
3 raised to the power of 3 = 27
3 raised to the power of 4 = 81
3 raised to the power of 5 = 243
3 raised to the power of 6 = 729
3 raised to the power of 7 = 2187
3 raised to the power of 8 = 6561
Process finished with exit code 0
コードの変更に注意してください。これを前提条件のあるループと比較してください。
ループの操作に関する興味深い事実
ループ本体内の分岐ステートメント
ループ内の実行に影響を与えるステートメントは 2 つあります。break (次の章で詳しく説明します) と- continue — 現在の反復でループ本体の残りの実行をスキップし、while ステートメントのブール式の評価にジャンプします。式が true と評価されると、ループが続行されます。
- Break — 現在の反復の実行を直ちに終了し、ループ後の最初のステートメントに制御を移します。したがって、このステートメントは現在のループの実行を終了します。次の記事でさらに詳しく検討します。
while (numberOfApplesInBowl > 0) {
apple = bowl.grabNextApple();
numberOfApplesInBow--; // "--" is the decrement operator, which reduces the number of apples by one
if (apple.isBad()) { // This method returns true for rotten apples
apple.throwInGarbage();
continue; // Continue the loop. Jump to evaluation of numberOfApplesInBowl > 0
}
arrangeInPie(apple.peel().slice());
}
continueステートメントは、特定の条件が満たされた場合にループ本体内のステートメントを実行する必要がある場合によく使用されます
。たとえば、ハードウェア センサーがトリガーされたときにアクションを実行したい場合があります (そうでない場合は、センサーの読み取り値を取得するループを継続するだけです)。または、ループの特定の反復でのみ式を計算したい場合があります。後者の例は、while ループを使用して、二乗が数値の数より小さい自然数の 3 乗の合計を計算するときに見ることができます。混乱している?次のコードを確認してください。
public static void main(String[] args) {
int sum = 0; // Total amount
int i = 0; // Initial number in the series
int count = 20; // Number of numbers
while (i <= count) {
i++; // Get the next number — "i++" is equivalent to "i = i + 1"
if (i * i <= count) // If the square of the number is less than
continue; // the number of numbers, then we won't calculate the sum
// Jump to the next number in the loop
sum += i * i * i; // Otherwise, we calculate the sum of the cubes of numbers
} // "sum += i * i * i" is notation that is equivalent to "sum = sum + i * i * i"
System.out.println(sum); // Print the result
}
無限ループ
これらの分岐ステートメントは、無限ループで最もよく使用されます。ループを終了するためのブール条件が決して満たされない場合、そのループを無限ループと呼びます。コードでは次のようになります。
while (true) {
// Loop body
}
この場合、
breakステートメントはループを終了するのに役立ちます。このタイプのループは、ループ本体の外側で決定される外部条件を待機する場合に適しています。たとえば、オペレーティング システムやゲームです (ループを終了することはゲームを終了することを意味します)。または、ループの各反復で何らかの結果を改善しようとするアルゴリズムを使用する場合でも、経過時間や外部イベント (チェッカー、チェス、天気予報など) の発生に基づいて反復回数を制限します。通常の状況では、無限ループは望ましくないことに注意してください。実証するために、べき乗に戻りましょう。
public static void main(String[] args) {
int base = 3; // The number that will be exponentiated
int result = 1; // The result of exponentiation
int exponent = 1; // The initial exponent
while (true) {
result = result * base;
System.out.println(base + " raised to the power of " + exponent + " = " + result);
exponent++;
if (exponent > 10)
break; // Exit the loop
}
}
コンソール出力:
3 raised to the power of 1 = 3
3 raised to the power of 2 = 9
3 raised to the power of 3 = 27
3 raised to the power of 4 = 81
3 raised to the power of 5 = 243
3 raised to the power of 6 = 729
3 raised to the power of 7 = 2187
3 raised to the power of 8 = 6561
3 raised to the power of 9 = 19683
3 raised to the power of 10 = 59049
Process finished with exit code 0
入れ子になったループ
さて、ループに関する最後のトピックに移ります。アップルパイ (お腹が空いていないことを祈ります) とリンゴの皮をむくループを思い出してください。-
ボウルの中にリンゴがある場合は、ステップ 1.1 から 1.4 を実行します。
- 1.1. リンゴを掴む
- 1.2. 皮をむいてスライスします
- 1.3. リンゴのスライスをパイ生地の中に並べてフライパンに並べる
- 1.4. 手順 1 に戻ります。
- スライスの数 = 0
-
スライスの数が 12 未満である限り、ステップ 2.1 ~ 2.3 を実行します。
- 2.1. リンゴをさらにスライスします
- 2.2. スライス数++
- 2.3. ステップ2に戻る
-
ボウルの中にリンゴがある場合は、ステップ 1.1 から 1.6 を実行します。
- 1.1. リンゴを掴む
- 1.2. 皮をむく
- 1.3. スライスの数 = 0
- 1.4. スライスの数が 12 未満である限り、ステップ 1.4.1 から 1.4.3 を実行します。
- 1.4.1. リンゴをさらにスライスします
- 1.4.2. スライス数++ 1.4.3. ステップ1.4に戻る
- 1.5. リンゴのスライスをパイ生地の中に並べてフライパンに並べる
- 1.6. 手順 1 に戻ります。
public static void main(String[] args) {
// Print the second factors in a row
System.out.println(" 2 3 4 5 6 7 8 9");
int i = 2; // Assign the first factor to the variable
while (i < 10) { // First loop: execute as long as the first factor is less than 10
System.out.print(i + " | "); // Print the first factor at the beginning of the line
int j = 2; // The starting value of the second factor
while (j < 10) { // Second loop: execute as long as the second factor is less than 10
int product = i * j; // Calculate the product of the factors
if (product < 10) // If the product is a single digit, then we print two spaces after the product
System.out.print(product + " ");
else // Otherwise, print the product and one space after it
System.out.print(product + " ");
j++; // Increment the second factor by one
} // Go to the beginning of the second loop, i.e. "while (j < 10)"
System.out.println(); // Move to the next line on the console
i++; // Increment the first factor by one
} // Go to the beginning of the first loop, i.e. "while (i < 10)"
}
コンソール出力:
2 3 4 5 6 7 8 9
2 | 4 6 8 10 12 14 16 18
3 | 6 9 12 15 18 21 24 27
4 | 8 12 16 20 24 28 32 36
5 | 10 15 20 25 30 35 40 45
6 | 12 18 24 30 36 42 48 54
7 | 14 21 28 35 42 49 56 63
8 | 16 24 32 40 48 56 64 72
9 | 18 27 36 45 54 63 72 81
Process finished with exit code 0
ループ (特に
whileステートメント) は、ソフトウェアの基本的な構成要素の 1 つです。CodeGym のタスクを解決することで、さまざまな種類のループをすべて学び、その複雑さを理解し、それらを使用するための実践的なスキルを身につけることができます。
GO TO FULL VERSION