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


当前回答

break语句会导致它所应用的语句(switch、for、do或while)的终止。

continue语句用于结束当前循环迭代并将控制权返回给循环语句。

其他回答

下面是break的语义:

int[] a = new int[] { 1, 3, 4, 6, 7, 9, 10 };
// find 9
for(int i = 0; i < a.Length; i++)
{
    if (a[i] == 9) 
        goto goBreak;

    Console.WriteLine(a[i].ToString());      
}
goBreak:;

下面是continue的语义:

int[] a = new int[] { 1, 3, 4, 6, 7, 9, 10 };
// skip all odds
for(int i = 0; i < a.Length; i++)
{
    if (a[i] % 2 == 1) 
        goto goContinue;

    Console.WriteLine(a[i].ToString());      

goContinue:;
}

简单的例子:

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完全离开循环,并在循环之后执行语句。 而Continue则离开当前迭代并执行循环中的下一个值。

这段代码解释了一切:

public static void main(String[] args) {
    for(int i=0;i<10;i++)
    {
        if (i==4)
        {
            break;
        }
        System.out.print(i+"\t");

    }
    System.out.println();
    for(int i=0;i<10;i++)
    {

        if (i==4)
        {
            continue;
        }
        System.out.print(i+"\t");
    }
}

输出:

0   1   2   3   
0   1   2   3   5   6   7   8   9

break语句跳出循环(要执行的下一个语句是右大括号之后的第一个语句),而continue语句在下一个迭代中开始循环。

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

打破

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

继续

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