2014-02-27

Java 的二三事 - 迴圈 loop

迴圈要項
  • 設定控制變數 Control Variable
  • 條件 Condition
  • 調整控制變數值 Control Value
Example for While:
//========== -begin- =============
public class WhileTest {
   public static void main (String [ ] args) {
         int i  = 10;                                                 //==> 設定控制變數
         while (i > 0) {                                            //==> 條件
              System.out.println (i);
              i --;                                                      //==> 調整控制變數 (由 i 值遞減)
          }
    }
}
//========== -end- ==============

Example for For:
//========== -begin- =============
public class ForTest {
     public static void main ( String [ ] args ) {
           for ( int i = 10; i > 10; i-- ) {                    //==> 要項全寫在小括弧內.
                System.out.println ( i );
           }
      }
}
//========== -end- ==============

Example output:
10
9
8
7
6
5
4
3
2
1

習慣於 While 與 For 的使用

for 迴圈通常用於具有明確重複次數的迴圈.
      因為全部的控制機制都放在 for 之後的小括弧中.

while 迴圈用法為較不明確的重複次數.
        程式通常被設計成一直等待使用者的輸入, 迴圈才會結束.




沒有留言:

張貼留言