break語句/Continue語句的新認識
阿新 • • 發佈:2019-02-16
break語句在java中的語法格式居然是:
'break' [label] ';'
在java的程式設計生涯中還沒看到break語句有這樣子出現的,有點的bat中的goto語句,不過bat是前面設定好label標籤,然後用goto語句跳轉到label標籤處重新執行一次。而break語句是指跳出該標籤指定的迴圈控制語句:
like:
outerwhile: while(true) { System.out.println("\n True/False: Blocks can be nested.\n"); innerwhile1: while(true) { System.out.print("Enter t,f or any key to exit quit."); switch(System.in.read()) { case 't': System.out.println("You are correct."); while (System.in.read() != '\n'); break innerwhile1; case 'f': System.out.println("You are wrong."); while (System.in.read() != '\n'); break; default: break outerwhile; } } innerwhile2: while(true) { System.out.print("Enter t, f or any key to exit quit."); switch(System.in.read()) { case 't': System.out.println("You are wrong."); while(System.in.read() != '\n'); break; case 'f': System.out.println("You are correct."); while(System.in.read() != '\n'); break innerwhile2; default: break outerwhile; } } } System.out.println("Quiz has terminated");
恰巧有一個Continue語句是可以跟goto語句是類似的如下:
couterFor:
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if((i - 3) == 0) {
continue couterFor;
}
System.out.println((float)j/(i-3));
}
}
以上的 程式碼中使用了標籤,這樣就可以避免被零除的情況。