break和continue详解for循环

2020-01-03 00:36:00

参考链接 Java:break和continue关键字的作用

二者的作用和区别

1. break:直接跳出当前循环体(while、for、do while)或程序块(switch)。其中switch case执行时,一定会先进行匹配,匹配成功返回当前case的值,再根据是否有break,判断是否继续输出,或是跳出判断(可参考switch的介绍)。

2. continue:不再执行循环体中continue语句之后的代码直接进行下一次循环

 

代码演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Test {
    public static void main(String[] args) {
        System.out.println("-------continue测试----------");
        for (int i = 0; i < 5; i++) {
            if (i == 2) {
                System.out.println("跳过下面输出语句,返回for循环");
                continue;
            }
             
            System.out.println(i);
        }
 
 
        System.out.println("----------break测试----------");
        for (int i = 0; i < 5; i++) {
            if (i == 2) {
                System.out.println("跳过下面输出语句,返回for循环");
                break;
            }
            System.out.println(i);
        }
 
    }
}

  运行结果:

可以看到测试 continue时,当 i==3,直接跳过了continue之后的输出语句,进入下一次循环。

在break测试中,当 i==2,直接跳出了 for 循环,不再执行之后的循环


  • 2019-09-23 16:17:13

    consola 教程

    consola 和 console 只差一个字母,并且它们都是控制器日志输出的好帮手。console 在某些方面,使用有些局限性。consola 是一个功能更丰富,更漂亮的控制台日志输出控件。今天我们一起来学习它的

  • 2019-09-24 22:03:13

    nginx支持socket

    安装nginx,stream模块默认不安装的,需要手动添加参数:–with-stream,根据自己系统版本选择nginx1.9或以上版本。

  • 2019-09-26 13:25:38

    git合并时冲突<<<<<<< HEAD

    head 到 =======里面的lalala是自己的commit的内容 =========到 >>>>>>里面的hehehe是下拉的内容

  • 2019-09-26 18:57:29

    Java中数组怎么深度复制

    有时候循环进行一些操作,放入list,发现,list中的数据都是一个数据,这就尴尬了,我们需要深度复制,才能解决这个问题。或者生成新的,也就是深度复制。

  • 2019-09-26 19:03:33

    spring post jackson的反序列化需要无参构造函数

    JSON parse error: Cannot construct instance of `com.**` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.**` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)  at [Source: (PushbackInputStream); line: 2, column: 2]] ———————————————— 版权声明:本文为CSDN博主「冰夏之夜影」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/u011561335/article/details/91346777