Java do while循环语句用法

do-while循环,先执行一次,然后在判断,如果条件成立,在循环执行,如果不成立,继续往下执行

语法

do {
     statement(s)
} while (expression);

布尔表达式在循环体的后面,所以语句块在检测布尔表达式之前已经执行了。如果布尔表达式的值为 true,则语句块一直执行,直到布尔表达式的值为 false。

与while区别

while循环语句只有循环条件满足时,才执行循环体;不满足,则跳过循环体!do while 循环语句至少执行一次循环,实例如下:

public class Test{
    public static void main(String[] args){
        int i    =    1;
        do{
            System.out.println(i);
            i++;
        }
        while(i<30); //do-while循环,先执行一次,然后在判断,如果条件成立,在循环执行,如果不成立,继续往下执行 
    } 
} 

总结

do...while循环特点是先执行一次,执行完一次后再判断条件,满足条件了再执行,不满足条件就结束,换句话说,do...while和while的区别是,while先判断后执行,而do...while至少要执行一次。
do...while适合至少执行一次且循环次数不固定的时候,当循环次数固定的时候推荐使用for循环。

实例

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

语法示例


  1. public class WhileDemo {  
  2.       
  3.     public static void test(){  
  4.         int i=0;  
  5.         int j=0;  
  6.         int count=0;  
  7.         int count01=0;  
  8.         while(i<3){  
  9.             count++;  
  10.             i++;  
  11.         }  
  12.         do {  
  13.             count01++;  
  14.             j++;  
  15.         } while (j<3);  
  16.           
  17.         System.out.println(count);  
  18.         System.out.println("==============");  
  19.         System.out.println(count01);  
  20.     }  
  21.       
  22.       
  23.     public static void test01(){  
  24.         int i=0;  
  25.         int j=0;  
  26.         int count=0;  
  27.         int count01=0;  
  28.         while(i==3){  
  29.             count++;  
  30.             i++;  
  31.         }  
  32.         do {  
  33.             count01++;  
  34.             j++;  
  35.         } while (j==3);  
  36.           
  37.         System.out.println(count);  
  38.         System.out.println("==============");  
  39.         System.out.println(count01);  
  40.     }  
  41.     public static void main(String[] args) {  
  42.         WhileDemo.test();  
  43.         WhileDemo.test01();  
  44.     }  
  45. }  

运行结果为:

3
==============
3
0
==============
1