Java中的break和continue關鍵字使用筆記

來源:互聯網
上載者:User

Java中的break和continue關鍵字使用筆記
一、作用和區別 break的作用是跳出當前迴圈塊(for、while、do while)或程式塊(switch)。在迴圈塊中的作用是跳出當前正在迴圈的迴圈體。在程式塊中的作用是中斷和下一個case條件的比較。 continue用於結束迴圈體中其後語句的執行,並跳回迴圈程式塊的開頭執行下一次迴圈,而不是立刻迴圈體。 二、其他用途 break和continue可以配合語句標籤使用。這個都很簡單,下面給個綜合執行個體,看看就明白 了:
/**
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2007-11-29
* Time: 15:47:20
*/
public class Test {
    public static void main(String args[]) { 
        Test test = new Test ();
        test.testBreak1();

        test.testContinue1();

        test.testBreak2();
        test.testContinue2();
    }

    /**
    * 測試continue
    * continue用來結束本次迴圈
    */
    public void testContinue1() {
        System.out.println("--------測試continue-------");
        for (int i = 1; i <= 5; i++) {
            if (i == 3) continue;
            System.out.println("i=" + i);
        }
    }

    /**
    * break用來結束整個迴圈體
    */
    public void testBreak1() {
        System.out.println("--------測試break1-------");
        for (int i = 1; i <= 5; i++) {
            if (i == 3) break;
            System.out.println("i=" + i);
        }
    }

    /**
    * 測試帶標籤的break語句
    * 標籤只能寫在迴圈體之前,順便學習一下java中語句標籤的定義和使用
    */
    public void testBreak2() {
        System.out.println("--------測試break2-------");
        int i = 1;
        int k = 4;
        lable1:
        for (; i <= 5; i++, k--) {
            if (k == 0) break lable1;
            System.out.println("i=" + i + " ; k=" + k);
        }
    }

    public void testContinue2() {
        System.out.println("--------測試continue2-------");
        lable1:
        for (int i = 1; i < 10; i++) {
            lable2:
            System.out.println("i=" + i);
            for (int j = 0; j < 10; j++) {
                if (j == 9) continue lable1;
            }
        }
    }
} 運行結果:--------測試break1-------
i=1
i=2
--------測試continue-------
i=1
i=2
i=4
i=5
--------測試break2-------
i=1 ; k=4
i=2 ; k=3
i=3 ; k=2
i=4 ; k=1
--------測試continue2-------
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9

Process finished with exit code 0

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.