John Squirrels
等級 41
San Francisco

語句

在 Toto sisi 群組發布
我們的第一個程序是一個接一個執行的指令序列。沒有叉子。這包括顯示問候語的 HelloWorld。它包括算術計算。在我們的第一個程序之後,我們學習瞭如何分支,即如何使程序根據特定條件執行不同的操作。下面是控制中央供暖和空調系統的代碼:

if (tempRoom>tempComfort)
    airConditionerOn();
if (tempRoom<tempComfort)
    heaterOn();
採取下一步。在日常生活中,我們經常進行統一的重複動作,例如,削蘋果做餡餅。這個迷人的過程可以描述為:
  1. 如果碗裡有蘋果,那麼我們執行步驟1.1到1.4:

    1. 1.1. 拿一個蘋果
    2. 1.2. 去皮切成片
    3. 1.3. 把蘋果片放在平底鍋裡的餡餅皮里
    4. 1.4. 返回步驟 1。
while 語句 - 2假設你有十個蘋果、兩隻手和一把刀。在現實生活中,您按照每個蘋果的相同算法依次剝整打蘋果。但是我們如何讓一個程序對每個蘋果做一個重複的動作呢?
  • 我們將自己與蘋果的數量聯繫起來,但如果我們沒有足夠的蘋果,那麼一些命令將在沒有“有效負載”的情況下執行(我們可能會在嘗試剝一個不存在的蘋果時割傷自己)。
  • 如果蘋果的數量多於要剝皮的命令,那麼一些蘋果將不被剝皮。
  • 這樣的代碼很難閱讀。它有很多重複,很難修改。

循環是允許重複執行操作的語句

Java 的while循環在我們的例子中會很好地工作。此構造將多個操作放入一個簡潔易懂的結構中。使用while循環,一個派的蘋果切片算法在 Java 中可能看起來像這樣:

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
}
以下是執行此代碼時發生的情況的分步說明:
  1. 我們計算while關鍵字後括號中的布爾表達式。
  2. 如果布爾表達式的計算結果為真,則執行循環體中的語句。循環體中的最後一條語句執行完後,進入第1步
  3. 如果布爾表達式的計算結果為假,那麼我們跳轉到while循環之後的第一條語句。

有前提條件的循環

因為我們總是在執行循環體之前計算布爾表達式(進入循環的條件) ,所以這種形式的while循環通常被稱為帶前提條件的循環。讓我們建立一個數字的前十次冪的表:

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

帶後置條件的循環

這是此循環的第二個變體:

do {
    // Loop body — the statement(s) that are repeatedly executed
} while (Boolean expression);
以下是對執行此代碼時發生的情況的解釋:
  1. 循環體被執行(緊接在do關鍵字之後)。
  2. 我們計算while關鍵字後括號中的布爾表達式。
  3. 如果布爾表達式的計算結果為真,那麼我們轉到步驟 1
  4. 如果布爾表達式的計算結果為假,那麼我們跳轉到while循環之後的第一條語句。
與前一個循環的兩個主要區別是:1) 循環體至少執行一次,以及 2) 在循環體執行後計算布爾表達式。因此,這種while循環稱為帶後置條件的循環。這次我們將顯示一個不超過 10000 的數的冪表:

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
注意代碼的變化。將此與帶有前提條件的循環進行比較。

關於使用循環的有趣事實

循環體內的分支語句

有兩個語句會影響循環內的執行:break(我們將在下一章中更詳細地討論)和 繼續。
  • continue — 跳過當前迭代中循環體的其餘部分的執行並跳轉到 while 語句的布爾表達式的計算。如果表達式的計算結果為真,則循環繼續。
  • break — 立即終止當前迭代的執行並將控制轉移到循環後的第一條語句。因此,該語句結束當前循環的執行。我們將在下一篇文章中更詳細地討論它。
回想一下我們的水果示例。如果我們不確定蘋果的質量,我們可以使用 continue語句更改代碼:

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 循環計算平方小於數字個數的自然數的立方之和時,可以看到後一種情況的示例。使困惑?查看以下代碼:

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到1.4:

    1. 1.1. 拿一個蘋果
    2. 1.2. 去皮切成片
    3. 1.3. 把蘋果片放在平底鍋裡的餡餅皮里
    4. 1.4. 返回步驟 1。
讓我們更詳細地描述切片過程:
  1. 切片數 = 0
  2. 只要切片數 < 12,則執行步驟 2.1 到 2.3

    1. 2.1. 從蘋果上切下另一片
    2. 2.2. 片數++
    3. 2.3. 返回步驟 2
我們會將其添加到我們的餡餅製作算法中:
  1. 如果碗裡有蘋果,那麼我們執行步驟 1.1 到 1.6:

    1. 1.1. 拿一個蘋果
    2. 1.2. 去皮
    3. 1.3. 切片數 = 0
    4. 1.4. 只要切片數 < 12,然後執行步驟 1.4.1 到 1.4.3
      1. 1.4.1. 從蘋果上切下另一片
      2. 1.4.2. 片數++
      3. 1.4.3. 返回步驟 1.4
    5. 1.5. 把蘋果片放在平底鍋裡的餡餅皮里
    6. 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語句)是軟件的基本構建塊之一。通過在 CodeGym 上解決任務,您將了解所有不同類型的循環,了解它們的複雜性,並獲得使用它們的實用技能。
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION