这篇Java教程基于JDK1.8。教程中的示例和实践不会使用未来发行版中的优化建议。
while和do-while语句
while语句会在表达式为true的时候持续循环执行一个代码块,它的语法格式如下:
while ( expression ){
statement(s)
}
while语句计算表达式,必须返回一个boolean值。如果表达式运算结果为true,while语句就会执行其括号内的代码块。while语句持续的计算表达式并执行代码块直到表达式返回false。使用while语句打印从1到10的数字参见如下:
class WhileDemo{
public static void main(String[] args){
int count = 1;
while(count < 11){
System.out.println("Count is : " + count);
count++;
}
}
}
你可以像下文所示实现一个无限循环:
while(true){
//your code goes here
}
Java编程语言也提供了do-while语句,其表达形式如下:
do{
statement(s)
}while(expression);
do-while和while循环的唯一区别是条件表达式位于循环的结尾而不是开头,这也就意味着do-while循环中的do代码块至少会执行一次,下面的示例为你展示这个特性:
class DoWhileDemo{
public static void main(String[] args){
int count = 1;
do{
System.out.println("Count is : " + count);
count++;
}while(count < 11);
}
}