標籤:操作 public nbsp code others 開始 第一個 break 使用
break
break可用於迴圈和switch...case...語句中。
用於switch...case中:
執行完滿足case條件的內容內後結束switch,不執行下面的語句。
eg:
public static void breakSwitch1() { int n = 1; switch (n) { case 1: System.out.println("this is one."); break; case 2: System.out.println("this is two."); break; default: System.out.println("Others."); } }
結果:
this is one.
eg2:
public static void breakSwitch2() { int n = 1; switch (n) { case 1: System.out.println("this is one."); //break; case 2: System.out.println("this is two."); break; default: System.out.println("Others."); } }
結果:
this is one.
this is two.
如果不使用break語句則所有的操作將在第一個滿足條件之後的語句全部輸出,直到遇到break語句為止;
一、作用和區別 break的作用是跳出當前迴圈塊(for、while、do while)或程式塊(switch)。在迴圈塊中的作用是跳出當前正在迴圈的迴圈體。在程式塊中的作用是中斷和下一個case條件的比較。 continue用於結束迴圈體中其後語句的執行,並跳回迴圈程式塊的開頭執行下一次迴圈,而不是立刻迴圈體。
- 當迴圈執行到break語句時,就退出整個迴圈,然後執行迴圈外的語句。
-
當迴圈語句執行到continue時,當次迴圈結束,重新開始下一輪迴圈。如果已經是最後一輪迴圈了,那麼這是的continue就與break效果一樣了。
Java 中 break和 continue 的使用方法及區別