Java While語句

2018-06-16 14:44 更新

Java教程 - Java While語句


while循環(huán)在其控制條件為真時重復語句或塊。

Java while循環(huán)

這是它的一般形式:

while(condition) { 
   // body of loop 
}
  • 條件可以是任何布爾表達式。
  • 只要條件條件為真,循環(huán)的主體將被執(zhí)行。
  • 如果只重復單個語句,花括號是不必要的。

這里是一個while循環(huán),從10減少,打印十行“tick":

 
public class Main {
  public static void main(String args[]) {
    int n = 10;
    while (n > 0) {
      System.out.println("n:" + n);
      n--;
    }
  }
}

當你運行這個程序,你會得到以下結果:

例子

以下代碼顯示如何使用while循環(huán)來計算和。

public class Main {
  public static void main(String[] args) {
    int limit = 20;
    int sum = 0;
    int i = 1;

    while (i <= limit) {
      sum += i++;
    }
    System.out.println("sum = " + sum);
  }
}

上面的代碼生成以下結果。


例2

如果條件是 false ,則 while 循環(huán)的正文將不會執(zhí)行。例如,在以下片段中,從不執(zhí)行對 println()的調用:

 
public class Main {
  public static void main(String[] argv) {
    int a = 10, b = 20;
    while (a > b) {
      System.out.println("This will not be displayed");
    }
    System.out.println("You are here");
  }
}

輸出:

例3

while 的正文可以為空。例如,考慮以下程序:

 
public class Main {
  public static void main(String args[]) {
    int i, j;
    i = 10;
    j = 20;

    // find midpoint between i and j
    while (++i < --j)
      ;
    System.out.println("Midpoint is " + i);
  }
}

上面代碼中的 while 循環(huán)沒有循環(huán)體和 i j 在while循環(huán)條件語句中計算。它生成以下輸出:

Java do while循環(huán)

要執(zhí)行while循環(huán)的主體至少一次,可以使用do-while循環(huán)。

Java do while循環(huán)的語法是:

do { 
   // body of loop 
} while (condition);

這里是一個例子,顯示如何使用 do-while 循環(huán)。

 
public class Main {
  public static void main(String args[]) {
    int n = 10;
    do {
      System.out.println("n:" + n);
      n--;
    } while (n > 0);
  }
}

輸出:

前面程序中的循環(huán)可以寫成:

public class Main {
  public static void main(String args[]) {
    int n = 10;
    do {
      System.out.println("n:" + n);
    } while (--n > 0);
  }
}

輸出與上面的結果相同:

例4

以下程序使用 do-while 實現了一個非常簡單的幫助系統(tǒng)循環(huán)和 swith語句。

 public class Main {

  public static void main(String args[]) throws java.io.IOException {

    char choice;

    do {

      System.out.println("Help on:");

      System.out.println(" 1. A");

      System.out.println(" 2. B");

      System.out.println(" 3. C");

      System.out.println(" 4. D");

      System.out.println(" 5. E");

      System.out.println("Choose one:");

      choice = (char) System.in.read();

    } while (choice < '1' || choice > '5');

    System.out.println("\n");

    switch (choice) {

      case '1':

        System.out.println("A");

        break;

      case '2':

        System.out.println("B");

        break;

      case '3':

        System.out.println("C");

        break;

      case '4':

        System.out.println("D");

        break;

      case '5':

        System.out.println("E");

        break;

    }

  }

}

下面是這個程序生成的示例運行:


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號