標籤:blog pac ges alt ++ ima 迴圈控制 stat static
》while迴圈語句
while 迴圈執行個體圖:
不多說,先上例子:
package cn.bdqn;public class Test { public static void main(String[] args) { int num=1; //迴圈條件 num<= 10 while(num<=10){ System.out.println("第"+num+"次編寫代碼"); //迭代語句 num++; } }}
結果:
從上面可以看出while迴圈每次迴圈之前,先對迴圈條件求值,如果迴圈條件為true,則運行迴圈體部分。迭代條件總是位於迴圈體的最後,因此,只有迴圈體能成功執行完成,才能執行迭代語句。
在使用while迴圈時候一定要保證迴圈條件有變成false的時候,負責這個迴圈將變成一個死迴圈。
死迴圈執行個體:
package cn.bdqn;public class Test { public static void main(String[] args) { int num=1; //迴圈條件 num<= 10 while(num<=10){ System.out.println("第"+num+"次編寫代碼"); //迭代語句 //num++; } }}
結果:
在這段代碼當中num的值始終等於1,num<=10 迴圈條件一直為true,從而導致這個迴圈條件永遠沒法結束,就變成了死迴圈了。
》do while 迴圈語句
do while 迴圈與 while 迴圈的區別在於:while 先判斷迴圈條件,如果條件為真再執行迴圈體;而 do while 迴圈則先執行迴圈體,在判斷條件,如果條件為真,則執行下次迴圈,否則終止迴圈。
do while 迴圈執行個體圖:
執行個體:
public class Test { public static void main(String[] args) { int x=10; do{ System.out.println("value of x : " + x ); x++; }while(x<20); }}
與 while 迴圈不同的是,do while 迴圈的迴圈條件必須有一個分號,這個分號表明迴圈結束。
運行代碼結果:
迴圈條件的值開始就是假,do while迴圈也會執行迴圈體。因此,do while 迴圈的迴圈體至少執行一次。
下面代碼將驗證這個結論:
public class Test { public static void main(String[] args) { int x=21; do{ System.out.println("value of x : " + x ); x++; }while(x<20); }}
結果:
》 for迴圈
for 迴圈是更加 簡潔的迴圈語句,大部分情況下,for 迴圈可以代替 while 迴圈、do while 迴圈。for 迴圈的基本語句格式如下:
關於 for 迴圈有以下幾點說明:
》》最先執行運算式1。可以聲明一種類型,但可以初始化一個或多個迴圈控制變數,也可以是空語句。
》》然後檢查運算式2的值。如果是 true,迴圈體被執行。如果為 false,迴圈終止,開始執行迴圈體後面的語句。
》》執行一次迴圈後,更新迴圈控制變數。
》》再次執行運算式2,迴圈執行上面的過程。
執行個體
public class Test { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println("value of x : " + i); } }}
以上代碼執行結果:
容易出現的幾種問題:
public static void main(String[] args) { /* for (int i = 0;; i++) { //省略條件判斷,陷入了死迴圈 System.out.println(i); }*/ /*for (; ;) { //死迴圈 System.out.println(1); }*/ for (int i = 0; i < 10;) { // 省略了 條件判斷迭代變數 System.out.println(i); } }
Java——迴圈結構