Java——控制迴圈結構

來源:互聯網
上載者:User

標籤:++   tin   void   blog   ==   img   語言   for   system   

  在某些時候,我們需要在某種條件出現時,強行終止本次迴圈或結束迴圈,而不是等到迴圈條件為 false 時 ,在Java中提供了 continue (結束本次迴圈) 、break(跳出迴圈體)來控制迴圈結構。除此之外,return 可以結束整個方法,當然也就結束了一次迴圈。

 

break:用於完全結束一個迴圈 ,跳出迴圈體。

continue:中止本次迴圈,開始下次迴圈

 

public static void main(String[] args) {        int count=0; //列印次數初始值        for (int i = 1; i <=1000 ; i++) {            if(i%7==0)  //是7的倍數就進行下次迴圈                continue;            System.out.print(i+"\t");            count++;            if(count%4==0)                System.out.println();            if(i==100)                break;   //跳出迴圈        }            }

 

以上代碼運行結果:

 通過上面的例子我們可以看出 i = 7 或 7 的倍數,就開始下次迴圈,否則就列印,count 是記錄列印的次數,count 是 4 或 4 的倍數,就換行。i 等於 100 的時候就跳出迴圈體。

break 語句不光可以結束所在的迴圈,還可以直接結束其外層迴圈。此時,只需要在break語句後面緊跟一個標籤,這個標籤用於標識一個外層迴圈。

  java中的標籤就是一個緊跟著英冒號(:)的標識符。與其它語言不同的是,java中的標籤只有放在迴圈語句之前才有作用。

執行個體:

public static void main(String[] args) {        auter:        for (int i = 0; i < 10; i++) {                        for (int j = 0; j < 5; j++) {                if (j == 2) {                    System.out.print("第" + i + "次" + j);                    break auter;                }                            }            System.out.println();        }    }

 

結果:

 

 》使用 return 結束方法

  return 關鍵字不是專門用於跳出迴圈的, return 的功能是結束一個方法。當一個方法執行到一個 return  語句時(return 還可以跟變數、常量、運算式結合使用)這個方法將結束。

執行個體:

 

public static void main(String[] args) {                for (int i = 0; i < 10; i++) {                        for (int j = 0; j < 5; j++) {                if (j == 2) {                    System.out.print("第" + i + "次" + j);                    return;                }                            }            System.out.println();        }    }

 

 結果:

 

 

Java——控制迴圈結構

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.