--- title: Java SE笔记: while循环和do...while循环 date: 2016-07-21 21:30:00 updated: 2016-07-21 21:30:00 description: "while循环和do...while循环" categories: [个人笔记] tags: [Java, Java SE笔记] --- ### while循环 while是最基本的循环,它的结构为: ``` while( 布尔表达式 ) { //循环内容 } ``` 只要布尔表达式为true,循环体会一直执行下去。 有时程序也需要死循环。 实例 ```java public class Test { public static void main(String args[]) { int x = 10; while( x < 20 ) { System.out.print("value of x : " + x ); x++; System.out.print("\n"); } } } ``` 以上实例编译运行结果如下: ``` value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19 ``` ### do…while循环 对于while语句而言,如果不满足条件,则不能进入循环。但有时候我们需要即使不满足条件,也至少执行一次。 do…while循环和while循环相似,不同的是,do…while循环至少会执行一次。 ``` do { //代码语句 }while(布尔表达式); ``` 注意:布尔表达式在循环体的后面,所以语句块在检测布尔表达式之前已经执行了。 如果布尔表达式的值为true,则语句块一直执行,直到布尔表达式的值为false。 实例 ```java public class Test { public static void main(String args[]){ int x = 10; do { System.out.print("value of x : " + x ); x++; System.out.print("\n"); }while( x < 20 ); } } ``` 以上实例编译运行结果如下: ``` value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19 ```