zoukankan      html  css  js  c++  java
  • Java中跳出for循环的方法

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

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    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+" ");  

            }  

        }  

    }  

       

       

    输出:4

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    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+" ");  

            }  

        }  

    }  

       

    输出:9

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    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(" I'm here!");  

        }  

    }  

       

    输出:

    012345

    I'm here!

    想学习更多关于java的知识,可以点击小峰在线Java零基础进行学习。更多java学习课程,可以关注e良师益友

  • 相关阅读:
    微信跳一跳,Python辅助自动跳程序
    关于 adb devices找不到的解决方法
    vue--axios使用post方法与后台进行异步传值是报错POST http://localhost:8080/api/AddEmployeeApi 405 (METHOD NOT ALLOWED)
    vue 中引入外部css路径中使用@报错,提示找不到文件
    centos7服务器配置接口供外网调用
    排球计分程序改进
    排球计分程序(九)——总结
    排球计分程序(八)——验证编辑方法(Edit method)和编辑视图(Edit view)
    排球计分(七)—— 使用EF框架,创建Controller,生成数据库
    排球计分程序(六)——接口的设计与实现
  • 原文地址:https://www.cnblogs.com/xiaoxiao1/p/4064896.html
Copyright © 2011-2022 走看看