Java循环结构(执行多次)part1

1.while循环

(1)while是最基本的循环,它的结构为:
在这里插入图片描述
(2)只要布尔表达式为true,循环就会一直执行去下。
(3)我们大多数情况是会让循环停止下来,需要一个让表达式失效的方式来结束循环。
(4)少部分情况需要循环一直执行,如:服务器的请求、响应、监听等。
(5)循环条件为true就会造成死循环,我们正常的业务编程中应该尽量避免死循环。会影响程序性能或者造成程序卡死崩溃。
(6)输出1-100

package com.wang.struct;

public class WhileDemo01 {
    public static void main(String[] args) {
        //输出1~100
        int i = 0;

        while (i < 100) {   //先判断,i不能等于100
            i++;            //后自增
            System.out.println(i);
        }
    }
}

(7)输出1+2+…+100

package com.wang.struct;

public class WhileDemo02 {
    public static void main(String[] args) {

        int i = 0;
        int sum = 0;

        while (i < 100) {   //当i先自增,再求和的时候,布尔表达式中的i不能等于100
            i++;
            sum = sum+ i;
            System.out.println(sum);
        }
    }
}

2.do…while循环

(1)while语句,如果不满足条件,则不能进入循环。但有时候我们需要即使不满足条件,也至少执行一次。
(2)do…while循环和while循环相似,不同的是。do…while循环至少会执行一次。
在这里插入图片描述
在这里插入图片描述
(3)do…while写1+2+…+100

package com.wang.struct;

public class DoWhileDemo01 {
    public static void main(String[] args) {
        int i = 0;
        int sum = 0;

        do {    //先执行,总能保证循环体被执行至少一次
            i++;
            sum = sum + i;
            System.out.println(sum);
        }while (i<100); //后判断
    }
}

(4)while和do…while的输出差别

package com.wang.struct;

public class DoWhileDemo02 {
    public static void main(String[] args) {
        int a = 0;

        //while循环
        while (a<0){
            a++;
            System.out.println(a);
        }

        //输出分割线
        System.out.println("--------------");

        //do...while循环
        do {
            a++;
            System.out.println(a);
        }while (a<0);
    }
}

输出结果:
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值