全棧工程師之Java基礎篇(四)

Java 循環結構 - for, while 及 do...while

順序結構的程序語句只能被執行一次。若是您想要一樣的操做執行屢次,,就須要使用循環結構。程序員

Java中有三種主要的循環結構:數組

  • while 循環
  • do…while 循環
  • for 循環

while 循環

while(布爾類型){
    //語句
}

實例spa

public class Test {
   public static void main(String args[]) {
      int x = 10;
      while( x < 20 ) {
         System.out.print("x 值: " + x );
         x++;
         System.out.print("\n");
      }
   }
}

結果3d

 

do…while 循環

對於 while 語句而言,若是不知足條件,則不能進入循環。但有時候咱們須要即便不知足條件,也至少執行一次。code

do…while 循環和 while 循環類似,不一樣的是,do…while 循環至少會執行一次。blog

do {
       //代碼語句
}while(布爾表達式);

實例it

public class Test {
   public static void main(String args[]){
      int x = 10;
 
      do{
         System.out.print(" x值 : " + x );
         x++;
         System.out.print("\n");
      }while( x < 50 );
   }
}

結果for循環

 

for循環

雖然全部循環結構均可以用 while 或者 do...while表示,但 Java 提供了另外一種語句 —— for 循環,使一些循環結構變得更加簡單。class

for循環執行的次數是在執行前就肯定的。語法格式以下:變量

for(初始化; 布爾表達式; 更新) {
    //代碼語句
}

關於 for 循環有如下幾點說明:

  • 最早執行初始化步驟。能夠聲明一種類型,但可初始化一個或多個循環控制變量,也能夠是空語句。
  • 而後,檢測布爾表達式的值。若是爲 true,循環體被執行。若是爲false,循環終止,開始執行循環體後面的語句。
  • 執行一次循環後,更新循環控制變量。
  • 再次檢測布爾表達式。循環執行上面的過程。

實例

public class Test {
   public static void main(String args[]) {
 
      for(int x = 10; x < 12; x ++) {
         System.out.println(" x值 : " + x );
      }
   }
}

結果

 

Java 加強 for 循環

Java5 引入了一種主要用於數組的加強型 for 循環。

Java 加強 for 循環語法格式以下:

for(聲明語句 : 表達式)
{
   //代碼句子
}

實例

public class Test {
   public static void main(String args[]){
      int [] numbers = {10, 20, 30, 40, 50};//數組
 
      for(int x : numbers ){
         System.out.print( x );
         System.out.print(",");
      }
      System.out.print("\n");
      String [] names ={"1", "2", "3", "4"};
      for( String name : names ) {
         System.out.print( name );
         System.out.print(",");
      }
   }
}

結果

 

break 關鍵字

break 主要用在循環語句或者 switch 語句中,用來跳出整個語句塊。(避免無限循環)

break 跳出最裏層的循環,而且繼續執行該循環下面的語句。

語法

break 的用法很簡單,就是循環結構中的一條語句

實例

public class Test {
   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};
 
      for(int x : numbers ) {
         // x 等於 30 時跳出循環
         if( x == 30 ) {
            break;
         }
         System.out.println( x );
      }
   }
}

結果

 

continue 關鍵字

continue 適用於任何循環控制結構中。做用是讓程序馬上跳轉到下一次循環的迭代。

在 for 循環中,continue 語句使程序當即跳轉到更新語句。

在 while 或者 do…while 循環中,程序當即跳轉到布爾表達式的判斷語句。

語法

continue 就是循環體中一條簡單的語句:

實例

public class Test {
   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};
 
      for(int x : numbers ) {
         if( x == 30 ) {
        continue;
         }
         System.out.print( x );
         System.out.print("\n");
      }
   }
}

結果

 

通常對新手來講這麼多怎麼記住,其實程序員是多打出來才記得住了,去多看點實例,多打點代碼就懂這些循環怎麼用了

相關文章
相關標籤/搜索