循环语句——do…while语句

一、do while语句结构

do
{
    执行语句
}
while (条件表达式);

条件表达式必须是trur或false

 

二、do while语句特点

不论条件是否满足,都先执行一次执行语句

 

三、示例

1、先执行一次,变量的作用域在循环体外

class ForDemo
{
    public static void main(String[] args)
    {
        int x=1;
        do
        {
            System.out.println(x);
            x++;
        }
        while (x<3);
        System.out.println("x="+x);   //x=3
    }
}

输出结果:

1
2
x=3

 

2、与while的区别,在于先执行一次,再判断条件真或假,如下初始值和条件完全一致,运行结果不一样:

class ForDemo
{
    public static void main(String[] args)
    {
        int x=8;
        do
        {
            System.out.println("x="+x);
            x++;
        }
        while (x<3);
            System.out.println("x="+x);
    }
}    

输出结果:x=8

class ForDemo
{
    public static void main(String[] args)
    {
        int y=8;
        while (y<3)
        {
            System.out.println("y="+y);
            y++;
        }
    }
}

输出结果://无结果

 

posted @ 2017-02-07 08:30  自学开发的老司机  阅读(1074)  评论(0编辑  收藏  举报