【Java】Java_14 迴圈結構

來源:互聯網
上載者:User

標籤:span   列印   數值   system   結構   區別   lib   執行   部分   

迴圈結構

    當型:當P條件成立時(T),反覆執行A,直到P為“假”時才停止迴圈. 

    直到型:先執行A, 再判斷P,若為T,再執行A,如此反覆,直到P為F.

1.While迴圈

while迴圈的基本格式和流程圖:

while (布林運算式) {

  迴圈體;

}

while迴圈詳解:

在迴圈剛開始時,會計算一次“布林運算式”的值,若條件為真,執行迴圈體。而對於後來每一次額外的迴圈,都會在開始前重新計算一次。

語句中應有使迴圈趨向於結束的語句,否則會出現無限迴圈–––"死"迴圈

 while迴圈代碼:

/** * 測試while迴圈 */package com.oliver.test;public class TestWhile {    public static void main(String[] args) {        //列印1到100        int a = 1;        while (a<=100){            System.out.println(a);            a++;        }        //求1到100的和        int b = 1 ;        int sum = 0;        while(b<=100){            sum += b;            b++;                }        System.out.println(sum);    }}
2.do-while迴圈do-while迴圈的基本格式:                     

do {

  迴圈體;

  } while(布林運算式) ;

 

do-while迴圈說明和流程圖:

1.    先執行迴圈體

2.    後判斷布林運算式

3.    迴圈體至少執行一次

do-while迴圈代碼:

 

package com.oliver.test;public class Dowhile {    public static void main(String[] args) {        int i = 1;        do{            i = i+1;            i++;        }        while(i<=10);            System.out.println("i的數值為"+i);            }}

 

while與do-while的區別

while      先判斷,後執行

dowhile    先執行,後判斷

3. for迴圈 

for迴圈語句是支援迭代的一種通用結構,是最有效、最靈活的迴圈結構

文法形式

         for (初始運算式;布林運算式;步進) { 

         迴圈體;

         }

for迴圈在第一次反覆之前要進行初始化。隨後,它會進行條件測試,而且在每一次反覆的時候,進行某種形式的“步進”。

  1. 初始化部分設定迴圈變數的初值
  2. 條件判斷部分為任意布林運算式
  3. 迭代因子控制迴圈變數的增減

【注意】for迴圈在執行條件測試後,先執行程式部分,再執行步進。

for迴圈代碼:

/** * 測試for迴圈 * Author:OLIVER */package com.oliver.test;public class TestFor {    public static void main(String[] args) {        for(int i=1;i<=10;i++){            System.out.println(i);        }    }}

 

【Java】Java_14 迴圈結構

聯繫我們

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