有人能告诉我break语句和continue语句的区别吗?


当前回答

简单的例子:

Break离开了循环。

int m = 0;
for(int n = 0; n < 5; ++n){
  if(n == 2){
    break;
  }
  m++;
}

System.out.printl("m:"+m); // m:2

Continue将返回开始循环。

int m = 0;
for(int n = 0; n < 5; ++n){
  if(n == 2){
    continue; // Go back to start and dont execute m++
  }
  m++;
}

System.out.printl("m:"+m); // m:4

其他回答

Break只留下一个循环,继续跳转到下一个迭代。

有关更多细节和代码示例,请参阅分支语句:

打破

break语句有两种形式:有标记的和无标记的。你们看到了 switch语句中未标记的形式。你 还可以使用未标记的中断来终止for, while或do-while吗 循环[…] 未标记的break语句终止最里面的开关,如下: While或do-while语句,但是标记的break终止了外层语句 声明。

继续

continue语句跳过for语句的当前迭代, 或者do-while循环。未标记的表单跳转到最内层的末尾 对象的布尔表达式求值 循环。[…] 带标签的continue语句跳过使用给定标签标记的外部循环的当前迭代。

continue跳过当前正在执行的循环并移动到下一个循环,而break移出循环并在循环后执行下一个语句。 我使用下面的代码了解了其中的区别。查看不同的输出。希望这能有所帮助。

public static void main(String[] args) {
    for(int i = 0; i < 5; i++){
        if (i == 3) {
            continue;
        }
        System.out.print(i);
    }
}//prints out 0124, continue moves to the next iteration skipping printing 3

public static void main(String[] args) {
    for(int i = 0; i < 5; i++){
        if (i == 3) {
            break;
        }
        System.out.print(i);
    }
}//prints out 012, break moves out of the loop hence doesnt print 3 and 4
for (int i = 1; i <= 3; i++) {
        if (i == 2) {

            continue;
        }
        System.out.print("[i:" + i + "]");

在netbeans中尝试这段代码,您将理解break和continue之间的区别

for (int i = 1; i <= 3; i++) {
        if (i == 2) {

            break;
        }
        System.out.print("[i:" + i + "]");

为了在满足条件时阻止执行任何东西,应该使用continue,如果满足条件,则应该使用break退出循环。

例如下面提到的代码。

 for(int i=0;i<5;i++){

        if(i==3){

           continue;

        }
       System.out.println(i);
     }

上面的代码将打印结果:0 1 2 4

现在考虑这段代码

 for(int i=0;i<5;i++){


            if(i==3){

                break;

            }
            System.out.println(i);
         }

这段代码将输出0 12

这就是continue和break的基本区别。