昨天我們說有4類程序控制語句,但是才講了2個。今天講跳轉(zhuǎn)語句。異常處理語句我們找一節(jié)專題來講。
循環(huán)跳轉(zhuǎn)語句 :break [label] //用來從語句、循環(huán)語句中跳出。
continue [label] //跳過循環(huán)體的剩余語句,開始下一次循環(huán)。
這兩個語句都可以帶標簽(label)使用,也可以不帶標簽使用。標簽是出現(xiàn)在一個語句之前的標識符,標簽后面要跟上一個冒號(:),標簽的定義如下:
label:statement;
實踐:
1、 break語句
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("Loop complete.");
}
} 5個break跳出循環(huán)的例子下載
//跳出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.");
}
}
} 這個在昨天的分支語句中,我們就已經(jīng)學到了。
2、 continue語句
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("");
}
}
}
//帶標簽的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();
}
} 此例子打包下載