JAVA中的break[標籤]continue[標籤]用法

來源:互聯網
上載者:User

標籤:

原文:JAVA中的break[標籤]continue[標籤]用法

注意:JAVA中的標籤必須放在迴圈之前,且中間不能有其他語句。例如:tag:for或while或do--while;

 

1.使用break退出一層迴圈(與C/C++中的break用法一樣)

 

 1 public static void main(String args[]) 2 { 3 int i=0; 4 while(i<100) 5 {  6 if(i==10) break; 7 System.out.println("i="+i); 8 i++; 9 }10 }

 


Attention:當break用在一組嵌套迴圈時,將僅跳出最裡面的迴圈。

2.使用break退出多層迴圈(與C/C++中的goto用法類似,跳過與標籤最近的即最外層迴圈)

 

 1 public static void main(String args[]) 2 { 3 outer: 4 for(int i=0; i<3; i++) 5 { 6 System.out.print("Pass "+i+":"); 7 for(int j=0; j<100; j++) 8 { 9 if(j==10)10 break outer;11 System.out.print(j+" ");12 }13 System.out.println("This will not print");14 }15 System.out.println("loops complete.");16 }

 


程式的輸出:
Pass 0: 0 1 2 3 4 5 6 7 8 9 loops complete.

continue的使用
1.在一層迴圈中的使用(與C/C++中的用法一樣)

 

 1 public static void main(String args[]) 2 { 3 for(int i=0; i<10; i++) 4 { 5 System.out.print(i+" "); 6 if(i%2==0) 7 continue; 8 System.out.println(""); 9 }10 }

 


輸出結果:
0 1
2 3
4 5
6 7
8 9

2.在多層迴圈中使用(提前結束的是標籤最近的最外層迴圈體的一次迴圈,提前進入最外層迴圈的下次迴圈)

 

 1 public static void main(String args[]) 2 { 3 outer: 4 for(int i=0; i<10; i++) 5  6 for(int k=0;k<10;k++) 7  8 { 9 for(int j=0; j<10; j++)10 {11 if(j>i)12 {13 System.out.println();14 continue outer;15 }16 System.out.print(" "+(i*j));17 }}18 19 System.out.println();20 }

 


 

0
0 1
0 2 4
0 3 6 9
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81

JAVA中的break[標籤]continue[標籤]用法

聯繫我們

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