iT邦幫忙

DAY 7
0

Java重點學習筆記系列 第 7

Java重點筆記六:Java的迴圈控制

Java一共有三個迴圈控制指令:

一、while

二、do...while

三、for

While迴圈

While (判斷式)
{
    ...
}

While迴圈可能一次都不執行。

public class Test {

   public static void main(String args[]) {
      int x = 1;

      while( x < 10 ) {
         System.out.print("value of x : " + x );
         x++;
         System.out.print("\n");
      }
   }
}

do..while迴圈

do
{
    ...
}while (判斷式)

do...while先執行,再判斷,所以至少執行一次。

public class Test {

   public static void main(String args[]){
      int x = 1;

      do{
         System.out.print("value of x : " + x );
         x++;
         System.out.print("\n");
      }while( x < 10 );
   }
}

for迴圈

for(初始值; 表達式; 更新)
{
    ...
}





public class Test {

   public static void main(String args[]) {

      for(int x = 1; x < 10; x = x+1) {
         System.out.print("value of x : " + x );
         System.out.print("\n");
      }
   }
}

陣列專用for迴圈

for(declaration : expression)
{
   ...
}






public class Test {

   public static void main(String args[]){
      int [] numbers = {1, 2, 3, 4, 5};

      for(int x : numbers ){
         System.out.print( x );
         System.out.print(",");
      }
      System.out.print("\n");
      String [] names ={"A", "B", "C", "D"};
      for( String name : names ) {
         System.out.print( name );
         System.out.print(",");
      }
   }
}

中斷迴圈:break

在迴圈或switch中使用break,可以直接中斷迴圈。

public class Test {

   public static void main(String args[]) {
      int [] numbers = {1, 2, 3, 4, 5};

      for(int x : numbers ) {
         if( x == 3 ) {
          break;
         }
         System.out.print( x );
         System.out.print("\n");
      }
   }
}

以上程式只會輸出:1跟2。

跳過一次迴圈:continue

continue用來跳過一次迴圈中的程式。

public class Test {

   public static void main(String args[]) {
      int [] numbers = {1, 2, 3, 4, 5};

      for(int x : numbers ) {
         if( x == 3 ) {
          continue;
         }
         System.out.print( x );
         System.out.print("\n");
      }
   }
}

輸出:
1
2
4
5

[image credit: Pavel Voinov]


上一篇
Java重點筆記五:Java的運算子
下一篇
Java重點筆記七:Java的選擇判斷語句
系列文
Java重點學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言