Java學習筆記15

來源:互聯網
上載者:User

標籤:變數   編寫   rgs   stat   pre   std   end   執行   welcome   

do-while迴圈時while迴圈的變體
文法如下:
do{
  // 迴圈體
 語句(組);
}while(迴圈繼續條件);

如果迴圈中的語句至少需要執行一次,那麼建議使用do-while迴圈.

for迴圈
常用以下的通用形式編寫迴圈:
i = initialValue;  // 初始化迴圈控制變數
while(i < endValue){
 // Loop body
 ...
 i++;  // 修改迴圈控制變數
}
可以用for迴圈簡化以上的迴圈:
for(i = initialValue; i < endValue; i++){
  // Loop body
  ...
}

使用for迴圈列印Welcome to Java!100次
for(int i = 0; i < 100; i++){
 System.out.println("Welcome to Java!");
}

注意:如果省略for迴圈中的迴圈繼續條件,則隱含地認為迴圈繼續條件為true.
for( ; ; ){
  // Do something
}

等價於:
for( ; true; ){
 // Do something
}

等價於:
while(true){
 // Do something
}

採用哪種迴圈:
1)若已知重複次數,就採用for迴圈
2)若無法確定重複次數,則採用while迴圈
3)若至少執行一次,則用do-while迴圈替代while迴圈.

 

package welcome;import java.util.Scanner;/* * 如果迴圈中的語句至少需要執行一次,那麼建議使用do-while迴圈 */public class TestDoWhile {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        int sum = 0;        int data;                do{            System.out.print("輸入一個整數,若輸入0程式將退出: ");            data = in.nextInt();                        sum += data;        }while(data != 0);                System.out.println("The sum is " + sum);    }}

 

Java學習筆記15

聯繫我們

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