首页 > 基础教程 > 循环条件语句 > 循环语句while

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

语法示例

publicclassWhileDemo {

publicstaticvoidtest(){

inti=0;

intj=0;

intcount=0;

intcount01=0;

while(i<3){

count++;

i++;

}

do{

count01++;

j++;

} while(j<3);

System.out.println(count);

System.out.println("==============");

System.out.println(count01);

}

publicstaticvoidtest01(){

inti=0;

intj=0;

intcount=0;

intcount01=0;

while(i==3){

count++;

i++;

}

do{

count01++;

j++;

} while(j==3);

System.out.println(count);

System.out.println("==============");

System.out.println(count01);

}

publicstaticvoidmain(String[] args) {

WhileDemo.test();

WhileDemo.test01();

}

}

运行结果为:

3

==============

3

0

==============

1

版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐