【JAVA SE基础篇】15.break和continue

1.break

break用来强行退出循环结构或者switch结构,不执行循环中剩余的语句。

例:(测试1-10随机几次可以随机到6)

while(true){
  count++;
  int a=(int)(10*Math.random());
  if(a==6){
    break;
  }
}
System.out.println("循环了"+count+"次得到6");

2.continue

continue用来结束某次循环结构,跳过剩余未执行的循环语句,执行新的一轮循环判断

例:(测试1-50之间不可以被3整除的数,并且每行输出5个)

int a=0;
for(int i=1;i<=50;i++){
  if(i%3==0){
    continue;
  }
  a++;
  System.out.print(i+" ");
  if(a%5==0){
    System.out.println();
  }
}

输出:

1 2 4 5 7
8 10 11 13 14
16 17 19 20 22
23 25 26 28 29
31 32 34 35 37
38 40 41 43 44
46 47 49 50

注:continue不能单独使用在switch,可以搭配循环使用在switch中。

原文地址:https://www.cnblogs.com/chengkuan/p/12872931.html