Java教程 - Java Break语句
当在循环中遇到 break
语句时,循环终止并进行程序控制在循环后的下一条语句中恢复。
break语句的语法
break;
或者
break labelName;
这里有一个简单的例子:
public class Main { public static void main(String args[]) { for (int i = 0; i < 100; i++) { if (i == 10) break; // terminate loop if i is 10 System.out.println("i: " + i); } System.out.println("Loop complete."); } }
此程序生成以下输出:

例子
break
语句可以与同时使用
循环。例如,这里是使用 while
循环编码的前面的程序。
public class Main { public static void main(String args[]) { int i = 0; while (i < 100) { if (i == 10) break; // terminate loop if i is 10 System.out.println("i: " + i); i++; } System.out.println("Loop complete."); } }
输出:

例2
break
语句有助于退出无限循环。在下面的 while
循环中, true
值是硬编码的,因此 while
循环是一个无限循环。 然后它使用 if
语句当 i
为10时, break
语句退出整个
循环。
public class Main { public static void main(String args[]) { int i = 0; while (true) { if (i == 10){ break; // terminate loop if i is 10 } System.out.println("i: " + i); i++; } System.out.println("Loop complete."); } }
输出:

例3
当在一组嵌套循环中使用时, break
语句只会突破最内层循环。 例如:
public class Main { public static void main(String args[]) { for (int i = 0; i < 5; i++) { System.out.print("Pass " + i + ": "); for (int j = 0; j < 100; j++) { if (j == 10) break; // terminate loop if j is 10 System.out.print(j + " "); } System.out.println(); } System.out.println("Loops complete."); } }
此程序生成以下输出:

例4
终止 switch 语句的 break
只会影响它 switch
语句,而不是任何封闭的循环。
public class Main { public static void main(String args[]) { for (int i = 0; i < 6; i++) switch (i) { case 1: System.out.println("i is one."); for (int j = 0; j < 5; j++) { System.out.println("j is " + j); } break; case 2: System.out.println("i is two."); break; default: System.out.println("i is greater than 3."); } } }
输出:

从结果我们可以看到 break
语句只退出 switch
语句。
例5
我们可以为break语句指定一个标签,让代码逻辑退出到那个点。 以下代码使用标签使break语句退出嵌套for循环的两个层。
public class Main { public static void main(String args[]) { outer: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (j + 1 < i) { System.out.println(); break outer; } System.out.print(" " + (i * j)); } } System.out.println(); } }
输出:
