循環(huán)跳轉(zhuǎn)語(yǔ)句 :break [label] //用來(lái)從語(yǔ)句、循環(huán)語(yǔ)句中跳出。
continue [label] //跳過(guò)循環(huán)體的剩余語(yǔ)句,開(kāi)始下一次循環(huán)。
這兩個(gè)語(yǔ)句都可以帶標(biāo)簽(label)使用,也可以不帶標(biāo)簽使用。標(biāo)簽是出現(xiàn)在一個(gè)語(yǔ)句之前的標(biāo)識(shí)符,標(biāo)簽后面要跟上一個(gè)冒號(hào)(:),標(biāo)簽的定義如下:
label:statement;
實(shí)踐:
1、 break語(yǔ)句
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
// 跳出循環(huán)
class BreakLoop {
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("
}
//跳出switch
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
} 這個(gè)在昨天的分支語(yǔ)句中,我們就已經(jīng)學(xué)到了。
2、 continue語(yǔ)句
class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
System.out.print(i + " ");
if (i%2 = = 0) continue;
System.out.println("");
}
}
}
//帶標(biāo)簽的continue
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j > i) {
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
} 此例子打包下載