Java:break和continue关键字的作用

二者的作用和区别

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

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

 

代码演示


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

  运行结果:

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

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

转载于:https://www.cnblogs.com/huiAlex/p/8242847.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值