W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
while循環(huán)在其控制條件為真時重復語句或塊。
這是它的一般形式:
while(condition) { // body of loop }
這里是一個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); } }
上面的代碼生成以下結果。
如果條件是 false
,則 while
循環(huán)的正文將不會執(zhí)行。例如,在以下片段中,從不執(zhí)行對 println()
的調(diào)用:
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"); } }
輸出:
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)條件語句中計算。它生成以下輸出:
要執(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); } }
輸出與上面的結果相同:
以下程序使用 do-while
實現(xiàn)了一個非常簡單的幫助系統(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;
}
}
}
下面是這個程序生成的示例運行:
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: