首頁  >  文章  >  Java  >  Java 中的 do-while 循環

Java 中的 do-while 循環

WBOY
WBOY原創
2024-08-30 15:25:08596瀏覽

從那時起,任何程式語言中都使用了循環。循環和迭代構成了程式語言的重要組成部分,無論是Java 還是Python;一種這樣的循環構造是Java 語言中的do-while 循環,它也通常稱為後增量循環,即循環構造肯定運行一次,然後匹配條件以運行下一次。時間等等。在本例中,條件被放在最後。換句話說,條件區塊繼續連續執行,除非且直到一組特定的條件稱為 true。

文法:

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

do
{
//block of statements
} while (expression);

while 區塊後面提到的表達式用於傳回布林值,即 true 值或 false 值。如果找不到其中任何一個值,則編譯器將引發編譯時錯誤。此語法中的 do 命令可確保程式碼至少執行一次,即使不執行表達式或不檢查條件也是如此。語句區塊是在 do-while 迴圈結構內執行的一組語句。這由程序主體組成。最後,while 語句用於計算表達式,然後應用後置條件來檢查預期的情況是否滿足要求,是否應該進一步循環。

Java 中 do-while 循環如何運作?

以下是 Java 中 do-while 循環如何運作的解釋:

  • 要使 do-while 循環工作,不需要滿足條件,因為即使不滿足條件,該循環第一次也能正常工作。然後編譯器執行器進入函數執行區塊執行語句區塊中的所有內容,然後出來檢查比較條件的表達式部分。如果滿足條件,則重複循環;否則,從區塊中退出循環。 while 和 do-while 迴圈之間的基本差異在於,前者尋找前置條件,而後者則針對後置條件。
  • do-while 和眾所周知的循環之間的基本差異在於,需要知道循環中的迭代次數以及初始值和正在遞增的值。當迭代及其計數固定數量時較常用,而在 do-while 迴圈的情況下,迭代次數事先未知,但可以動態變更。

流程圖:

Java 中的 do-while 循環

Java 中 do-while 循環的範例

以下是 10 之前所有數字的範例:

範例#1

列印所有小於等於 10 的數字。

代碼:

public class Main {
public static void main(String args [])
{
int c=1;
System.out.println("printing all the numbers till 10:");
do
{
//printing all the numbers till 10
System.out.println(c);
++c;
} while(c<11);
}
}

輸出:

Java 中的 do-while 循環

範例#2

使用 Java 中的 do-while 迴圈迭代數組。

代碼:

public class Main
{
public static void main(String args [])
{
int arr[]= {1, 6, 7, 514, 4, 98};
System.out.println("Printing the list of arrays: ");
//i in this case starts with 0 as the index in any looping statement has to start with the index of 0.
int i=0;
do
{
System.out.println(arr[i]);
++i;
} while (arr[i]<=6);
}
}

輸出:

Java 中的 do-while 循環

範例#3

為無限 do-while 迴圈編寫程式。

代碼:

public class Main
{
public static void main(String[] args)
{
do
{
System.out.println("infinite do while loop");
} while(true);
}
}

輸出:

Java 中的 do-while 循環

程式將無限地運行,直到程式碼區塊被明確破壞,因為無限迴圈命中 while 迴圈的條件為 true,這是一個 true 條件並且將始終滿足。因此,不鼓勵使用這些類型的循環和程式結構。如果它不包含適當的 RAM 和其他記憶體要求,它們可能會迷惑編譯器並掛起您的系統。

範例#4

以相反順序列印從 10 到 1 的所有數字。

代碼:

public class Main
{
public static void main(String args [])
{
int c=10;
System.out.println("Printing all the numbers from 10 till 1");
do
{
//printing all the numbers till 10
System.out.println(c);
--c;
} while(c>0);
}
}

輸出:

Java 中的 do-while 循環

範例#5

不使用增量運算子列印所有小於等於 10 的數字。

代碼:

public class Main
{
public static void main(String args [])
{
int c=1;
System.out.println("printing all the numbers till 10");
do
{
//printing all the numbers till 10 using shorthand operator
System.out.println(c);
c+=1;
} while(c<11);
}
}

輸出:

Java 中的 do-while 循環

此範例與第一個範例之間的基本差異在於,在本例中使用了簡寫運算符,在範例 1 中使用了預增量計數器。它們都會產生相同的結果;這只是您選擇要為 do-while 循環選擇哪個運算符的問題。

結論

在這篇文章中,我們看到了 do while 迴圈的基本介紹。我們也詳細了解了 do-while 循環的工作原理。我們看到了 do-while 迴圈相對於其他迴圈結構(例如 while 或 for 迴圈)的複雜性和主要差異以及應用。我們研究了do-while循環的流程圖,這有助於我們更深入地理解它。我們閱讀了語法和大量的各種示例,以清楚地理解 do-while 循環。

以上是Java 中的 do-while 循環的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn