當在循環(huán)中遇到 break
語句時,循環(huán)終止并進行程序控制在循環(huán)后的下一條語句中恢復(fù)。
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
語句可以與同時使用
循環(huán)。例如,這里是使用 while
循環(huán)編碼的前面的程序。
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."); } }
輸出:
break
語句有助于退出無限循環(huán)。在下面的 while
循環(huán)中, true
值是硬編碼的,因此 while
循環(huán)是一個無限循環(huán)。 然后它使用 if
語句當 i
為10時, break
語句退出整個
循環(huán)。
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."); } }
輸出:
當在一組嵌套循環(huán)中使用時, break
語句只會突破最內(nèi)層循環(huán)。 例如:
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."); } }
此程序生成以下輸出:
終止 switch 語句的 break
只會影響它 switch
語句,而不是任何封閉的循環(huán)。
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."); } } }
輸出:
從結(jié)果我們可以看到 break
語句只退出 switch
語句。
我們可以為break語句指定一個標簽,讓代碼邏輯退出到那個點。 以下代碼使用標簽使break語句退出嵌套for循環(huán)的兩個層。
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(); } }
輸出:
更多建議: