在switch語中,break語句用來終止switch語句的執行。使程序 switch語句后的第一個語句 開始執行。
在Java中,可以為每個代碼塊加一個括號,一個代碼塊通常 用大括號{}括起來的一段 代碼。加標號的格式
break語句有兩種形式:無標簽和有標簽。無標簽的break語句用來跳出單層switch、for、while、or do-while 循環,而有標簽的break語句則用來跳出嵌套的switch、for、while、or do-while語句。
BlockLabel:{codeBlock}
調出while
public class MainClass {
public static void main(String[] args) {
int i = 0;
while (true) {
System.out.println(i);
i ;
if (i > 3) {
break;
}
}
}
}
終止for循環
public class MainClass {
public static void main(String[] args) {
int count = 50;
for (int j = 1; j < count; j ) {
if (count % j == 0) {
System.out.println("Breaking!!");
break;
}
}
}
}
雙重循環
public class Main {
public static void main(String args[]) {
int len = 100;
int key = 50;
int k = 0;
out: {
for (int i = 0; i < len; i ) {
for (int j = 0; j < len; j ) {
if (i == key) {
break out;
}
k = 1;
}
}
}
System.out.println(k);
}
}
更復雜的
public class MainClass {
public static void main(String[] args) {
OuterLoop: for (int i = 2;; i ) {
for (int j = 2; j < i; j ) {
if (i % j == 0) {
continue OuterLoop;
}
}
System.out.println(i);
if (i == 37) {
break OuterLoop;
}
}
}
}
2
3
5
7
11
13
17
19
23
29
31
37