1. 程式人生 > >Java——循環結構

Java——循環結構

ava 條件判斷 表達式2 語句 技術分享 true pub log ack

  

》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——循環結構