如何在Java中使用Break and Continue语句?

Java编程语言中的break语句具有以下两种用法-

  • 当在循环内遇到break语句时,循环立即终止,程序控制在循环后的下一条语句处恢复。

  • 它可用于终止switch语句中的个案(在下一章中介绍)。

语法

break的语法是任何循环内的单个语句-

break;

示例

public class Test {
   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};
      for(int x : numbers ) {
         if( x == 30 ) {
            break;
         }
         System.out.print( x );
         System.out.print("\n");
      }
   }
}

输出结果

这将产生以下结果-

10
20

continue关键字可以在任何循环控制结构中使用。它使循环立即跳到循环的下一个迭代。

  • 在for循环中,continue关键字使控件立即跳转到update语句。

  • 在while循环或do / while循环中,控件立即跳转到布尔表达式。

语法

继续的语法是任何循环内的单个语句-

continue;

示例

public class Test {
   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};
      for(int x : numbers ) {
         if( x == 30 ) {
            continue;
         }
         System.out.print( x );
         System.out.print("\n");
      }
   }
}

输出结果

这将产生以下结果-

10
20
40
50