java do while 循环语句_Java do while循环语句用法

首页 > 基础教程 > 循环条件语句 > 循环语句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原创文章,未经本站允许不得转载。

  • 3
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值