原文出自 http://www.cnblogs.com/ggjucheng/archive/2012/12/16/2820841.html
英文出自 http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
while語句不斷執行塊里的語句,當特定條件是true。它的語句可以表述如下:
while (expression) {
statement(s)
}
while語句計算的表達式,必須返回boolean值。如果表達式計算為true,while語句執行while塊的所有語句。while語句繼續測試表達式,然后執行它的塊,直到表達式計算為false。使用while語句打印1到10的值,如WhileDemo程序:
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: "
+ count);
count++;
}
}
}
使用while語句實現無限循環如下:
while (true){
// your code goes here
}
java編程語言也支持do-while語句,表述如下:
do {
statement(s)
} while (expression);
do-while語句和while語句的區別是,do-while計算它的表達式是在循環的底部,而不是頂部。所以,do塊的語句,至少會執行一次,如DoWhileDemo程序所示:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: "
+ count);
count++;
} while (count < 11);
}
}
