Java中跳出循环的方法

Java中,如果想跳出for循环,一般情况下有两种方法:break和continue。

break是跳出当前for循环,如下面代码所示:

 1 package com.xtfggef.algo; 

 2 public class RecTest { 

 3     /**

 4      * @param args

 5      */ 

 6     public static void main(String[] args) { 

 7         for(int i=0; i<10; i++){ 

 8             if(i==5){ 

 9                 break; 

10             } 

11             System.out.print(i+" "); 

12         } 

13     } 

14 } 

输出:0 1 2 3 4
也就是说,break会跳出(终止)当前循环。

continue是跳出当前循环,开始下一循环,如下所示:

 1 package com.xtfggef.algo; 

 2 public class RecTest {

 3 

 4 /**

 5      * @param args

 6      */ 

 7     public static void main(String[] args) { 

 8         for (int i = 0; i < 10; i++) { 

 9             if (i == 5) { 

10                 continue; 

11             } 

12             System.out.print(i+" "); 

13         } 

14     } 

15 } 

输出:0 1 2 3 4 6 7 8 9

 

以上两种方法没有办法跳出多层循环,如果需要从多层循环跳出,则需要使用标签,定义一个标签label,然后再需要跳出的地方,用break label就行了,代码如下:

 1 package com.xtfggef.algo; 

 2 public class RecTest { 

 3  

 4     /**

 5      * @param args

 6      */ 

 7     public static void main(String[] args) { 

 8  

 9         loop: for (int i = 0; i < 10; i++) { 

10             for (int j = 0; j < 10; j++) { 

11                 for (int k = 0; k < 10; k++) { 

12                     for (int h = 0; h < 10; h++) { 

13                         if (h == 6) { 

14                             break loop; 

15                         } 

16                         System.out.print(h); 

17                     } 

18                 } 

19             } 

20         } 

21         System.out.println("\nI'm here!"); 

22     } 

23 } 

输出:

012345
I'm here!

原文链接地址:http://www.2cto.com/kf/201210/162380.html

你可能感兴趣的:(java)