JavaRush /Java Blog /Random-TW /Java 中的 While 循環

Java 中的 While 循環

在 Random-TW 群組發布

介紹

我們的第一個程式是一系列依序執行的指令。沒有叉子。這是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
假設您有 10 個蘋果、兩隻手和一把刀。在生活中,您會在相同演算法的指導下持續清理整個十個。如何讓程式對每個蘋果執行重複操作?
  • 讓我們將自己與蘋果的數量綁定起來,但是如果我們的蘋果數量很少,那麼一些命令將在沒有“有效負載”的情況下徒勞地執行(也許我們會在剝一個不存在的蘋果時割傷自己)。
  • 如果蘋果的數量多於我們的加工團隊,那麼有些產品將無法處理。
  • 這樣的「程式碼」難以閱讀,包含大量重複內容,且難以修改。

循環是多次執行操作的運算子。

Java while 迴圈(惡意迴圈)在我們的例子中運作良好。這種設計將多個動作組織成一個簡潔易懂的結構。在 Java 中切片蘋果做餡餅的 while 演算法可能如下所示:
while(числоЯблокВТазике>0) {
    яблоко = тазик.взятьОчередноеЯблоко();
    положитьВПирог(яблоко.чистить().нарезать());
    числоЯблокВТазике--;//-- this is a decrement, reduces the number of apples by one
}
System.out.println('Apples for the pie are processed.');

命令語法

第一種描述 while 語句的方式如下:
while(Логическое выражение) {
	// Loop body - periodically executed statement(s)
}
這是按如下方式完成的(一步一步):
  1. 我們評估括號中 while 後面的布林條件。
  2. 如果邏輯條件為真,則執行循環體中的運算符,執行完循環體中的最後一個運算子後,請轉到步驟1
  3. 如果邏輯條件為 false,則轉到 while 迴圈外的第一個語句。

有前提條件的循環

由於在執行迴圈體之前,我們總是預先計算一個邏輯表達式(進入迴圈的條件),因此這種類型的 while 通常稱為帶有前提條件的迴圈。讓我們建立一個包含前十個整數(數字的正冪)的表:
public static void main(String[] args) {
    int number = 3; // Number to be raised to a power
    int result = 1; // Result of exponentiation
    int power = 1; // Initial exponent
    while(power <= 10) { // loop entry condition
        result = result * number;
        System.out.println(number + "to the extent" + power + " = " + result);
        power++;
    }
}
控制台輸出結果:
3 в степени 1 = 3
3 в степени 2 = 9
3 в степени 3 = 27
3 в степени 4 = 81
3 в степени 5 = 243
3 в степени 6 = 729
3 в степени 7 = 2187
3 в степени 8 = 6561
3 в степени 9 = 19683
3 в степени 10 = 59049
Process finished with exit code 0

帶後置條件的循環

第二種循環:
do {
    // Loop body - periodically executed statement(s)
}while (Логическое выражение);
執行如下(步驟):
  1. 循環體被執行(緊接在 do 關鍵字之後)。
  2. 我們評估括號中 while 後面的布林條件。
  3. 若邏輯條件為真,則轉至步驟1
  4. 如果邏輯條件為 false,則轉到 while 迴圈外的第一個語句。
與先前類型的循環有兩個主要區別:循環體至少執行一次,並且在執行循環體後檢查邏輯條件。因此,這種類型的 while 迴圈稱為後置條件迴圈。這次我們將顯示一個不超過10000的數的冪表:
public static void main(String[] args) {
    int number = 3;// Number to be raised to a power
    int result = number;// Result of exponentiation
    int power = 1;// Initial exponent
    do {
        System.out.println(number + "to the extent" + power + " = " + result);
        power++;
        result = result * number;
    }while (result < 10000); // loop exit condition
控制台輸出結果:
3 в степени 1 = 3
3 в степени 2 = 9
3 в степени 3 = 27
3 в степени 4 = 81
3 в степени 5 = 243
3 в степени 6 = 729
3 в степени 7 = 2187
3 в степени 8 = 6561
Process finished with exit code 0
注意程式碼中的變化,將其與帶有前提條件的循環版本進行比較。

有關使用循環的有趣事實

循環體中的控制命令

有兩個指令會影響循環的進度:break,我們將在下一章中展示其功能,以及 繼續。
  • continue – 停止執行目前迴圈體並移至 while 運算子的邏輯運算式。如果計算的表達式為真,則循環的執行將繼續。
  • Break – 立即停止目前循環的執行並跳到其外部的第一個命令。因此,當前循環的執行被中斷。我們將在下一個主題中更詳細地討論它。
讓我們記住我們的水果例子。如果我們不確定所提供的蘋果的質量,我們可以使用以下命令更改程式碼 continue
while(числоЯблокВТазике>0) {
    яблоко = тазик.взятьОчередноеЯблоко();
    числоЯблокВТазике--;//-- this is a decrement, reduces the number of apples by one
    if (яблоко.плохое()) {  // method will return true for rotten, etc. apples
        яблоко.выкинутьВМусор();
        continue; // continue the loop, go to the condition number ofApplesIn the Basin>0
    }
    положитьВПирог(яблоко.чистить().нарезать());
}
continue當在循環體中需要在特定條件發生時執行命令時,通常會使用該結構,例如,在觸發設備中的感測器時執行操作(否則只需繼續讀取其指示器的循環) 或 最後一種情況的例子是在 while 循環中計算平方小於其數量的自然數的立方和:
public static void main(String[] args) {
    int sum = 0;    // total amount
    int i = 0;      // starting number of the row
    int count = 20; // amount of numbers
    while(i<=count) {
        i++;        // take the next number, i++ is equivalent to i=i+1
        if (i*i<=count)  // if the square of the number is less
            continue;   // number of numbers - do not count the sum
                        // move on to the next number in the loop
        sum += i*i*i; // otherwise, we calculate the sum of cubes of numbers
    } // sum += i*i*i - notation similar to sum = sum + i*i*i
    System.out.println(sum);// print result
}

無限循環

這些控制命令最常在無限循環中使用。之所以這樣稱呼,是因為邏輯退出條件永遠不會被滿足。在程式碼中它看起來像這樣:
while(true) {
    // Loop body
}
break在這種情況下,使用命令來組織退出 將很有用。當等待在循環體邏輯之外形成的外部條件時,會發生這種類型的循環。例如,在模擬英雄周圍的虛擬世界的遊戲中(退出循環=退出遊戲)、作業系統。或者,當使用演算法時,也許可以透過循環中的每個後續呼叫來改進結果,但透過時間或外部事件(跳棋、國際象棋或天氣預報)的發生來限制它們。應該記住,在正常情況下,無限循環是程式不穩定的問題之一。為了進行演示,讓我們回到數字的冪:
public static void main(String[] args) {
    int number = 3; // Number to be raised to a power
    int result = 1; // Result of exponentiation
    int power = 1; // Initial exponent
    while(true) {
        result = result * number;
        System.out.println(number + "to the extent" + power + " = " + result);
        power++;
        if (power>10)
            break; // exit from the loop
    }
}
控制台輸出結果:
3 в степени 1 = 3
3 в степени 2 = 9
3 в степени 3 = 27
3 в степени 4 = 81
3 в степени 5 = 243
3 в степени 6 = 729
3 в степени 7 = 2187
3 в степени 8 = 6561
3 в степени 9 = 19683
3 в степени 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.
Получor цикл в цикле. Подобные конструкции весьма частые. Для завершающего примера построим таблицу умножения, которые школьники 90-х видели на обложках тетрадей в младших классах.
運算子 while - 3
public static void main(String[] args) {
    // Display the values ​​of the second multiplier in the line
    System.out.println("    2  3  4  5  6  7  8  9");
    int i = 2;      // first multiplier, assign starting value
    while(i<10) {   // First loop, execute while the first multiplier is less than 10
        System.out.print(i + " | ");// Display the first multiplier at the beginning of the string
        int j = 2;                  // second multiplier, starting value
        while (j<10) { // Second loop, execute while the second multiplier is less than 10
            int mul=i*j; // Calculate the product of factors
            if (mul<10)  // If it contains one digit, print two spaces after it
                System.out.print(mul + "  ");
            else   // otherwise output the product and after it - one space
                System.out.print(mul + " ");
            j++;     // Increase the second multiplier by one,
        }            // Go to the beginning of the second loop (while (j<10 ).... )
        System.out.println(); // Move to the next line of output
        i++;                  // Increase the first multiplier by one,
    }                         // Go to the beginning of the first loop (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) – один из фундаментальных кирпичиков построения программ. Решая задачи на JavaRush, вы изучите все их разнообразие, разберёте тонкости функционирования и получите практические навыки их применения.
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION