Java 中 break和 continue 的使用方法及區別

來源:互聯網
上載者:User

標籤:操作   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用於結束迴圈體中其後語句的執行,並跳回迴圈程式塊的開頭執行下一次迴圈,而不是立刻迴圈體。 
  1. 當迴圈執行到break語句時,就退出整個迴圈,然後執行迴圈外的語句。
  2. 當迴圈語句執行到continue時,當次迴圈結束,重新開始下一輪迴圈。如果已經是最後一輪迴圈了,那麼這是的continue就與break效果一樣了。

 

 

 

Java 中 break和 continue 的使用方法及區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.