while
语句在特定条件为true
时连续执行语句块。它的语法可以表示为:
while (expression) {
statement(s)
}
while
语句对expression求值,该expression必须返回一个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);
}
}