循环语句——do…while语句

不问归期 提交于 2019-12-23 13:41:12

一、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++;
        }
    }
}

输出结果://无结果

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!