流程式控制制語句_for

來源:互聯網
上載者:User

標籤:style   blog   color   使用   for   問題   

for迴圈的格式:

  for (初始設定式;迴圈條件運算式 ;迴圈後的動作表達式 ){
     執行語句
}

public class ForDemo {    public static void main(String[] args) {                //int x = 3;只有程式讀到這時才在記憶體中開闢空間,而且只要for迴圈結束記憶體空間就會被釋放。        //第一個只要是合法的運算式就行,第二個一定要是條件運算式        for (int x = 3; x<8 ; x++ ){            System.out.println("x="+x);            //x只在該括弧內有效        }        //System.out.println("x======="x);//編譯錯誤,找不到x這個變數                        int y =3;        while(y<8)        {            System.out.println("y="+y);        }        System.out.println("y======="+y);//結果可以列印出y的值                        /*        1.變數有自己的範圍,對應for來說,如果將用於控制迴圈的增量定義在for語句中,那麼該變數只在for語句中有效        for語句執行完畢,該變數在記憶體中被釋放        2.for和while可以進行互換,用哪個都可以,但是如果需要定義迴圈增量,用for合適些,比較節省記憶體        */    }}

 

 

 for迴圈使用時常見的問題

for (System.out.println("a");System.out.println("b") ;System.out.println("c") ){            System.out.println("d");        }        //沒有結果,因為條件運算式既不是真也不是假所以沒結果
public class ForTest1 {    public static void main(String[] args) {        int x =1;        for (System.out.println("a");x<3 ;System.out.println("c") ){            System.out.println("d");            x++;//也可以放在for括弧後面,用逗號隔開就行            }        //結果是:a d c d c        //for(這裡可以多運算式只要用,隔開)        }}

 

 

無限迴圈的最簡單表現形式

for (; ; ){}//對於for語句條件運算式只要不寫預設就是true

while(true){}

流程式控制制語句_for

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.