教程集 www.jiaochengji.com
教程集 >  脚本编程  >  java  >  正文 Java中跳出循环函数break和continue使用例子

Java中跳出循环函数break和continue使用例子

发布时间:2016-10-25   编辑:jiaochengji.com
教程集为您提供Java中跳出循环函数break和continue使用例子等资源,欢迎您收藏本站,我们将为您提供最新的Java中跳出循环函数break和continue使用例子资源
在java中跳出循环我们会用到break和continue函数了,下面整理了几个例子,希望对各位了解break和continue会带来帮助哦。

在Java中,如果想跳出for循环,一般情况下有两种方法:break和continue。
break是跳出当前for循环,如下面代码所示:

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy7709')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy7709>public class RecTest { 
    
    /**
     * @param args
     */
    public static void main(String[] args) { 
        for(int i=0; i< 10; i ){ 
            if(i==5){ 
                break; 
            } 
            System.out.print(i " "); 
        } 
    } 

   
  
输出:0 1 2 3 4
也就是说,break会跳出(终止)当前循环。continue是跳出当前循环,开始下一循环,如下所示:

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy9964')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy9964>public class RecTest { 
    
    /**
     * @param args
     */
    public static void main(String[] args) { 
        for (int i = 0; i < 10; i ) { 
            if (i == 5) { 
                continue; 
            } 
            System.out.print(i " "); 
        } 
    } 

  
输出:0 1 2 3 4 6 7 8 9
   以上两种方法没有办法跳出多层循环,如果需要从多层循环跳出,则需要使用标签,定义一个标签label,
然后在需要跳出的地方,用break label就行了,代码如下:

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy7086')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy7086>

public class RecTest { 
    
    /**
     * @param args
     */
    public static void main(String[] args) { 
    
        loop: for (int i = 0; i < 10; i ) { 
            for (int j = 0; j < 10; j ) { 
                for (int k = 0; k < 10; k ) { 
                    for (int h = 0; h < 10; h ) { 
                        if (h == 6) { 
                            break loop; 
                        } 
                        System.out.print(h); 
                    } 
                } 
            } 
        } 
        System.out.println("nI'm here!"); 
    } 

  
输出:
012345
I'm here!

您可能感兴趣的文章:

[关闭]
~ ~