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);}}
