java基础语法-循环结构语句

本文详细介绍了Java中的do-while、while和for三种循环语句的工作原理,强调了do-while总是先执行一次的特点,while的条件判断后再执行,以及for循环的条件判断前置。同时提醒注意避免死循环导致的内存溢出问题。


前言

`
循环结构语句包括do-while或者while以及for循环


一、do-while语句

public class AppMain {

    public static void main(String[] args) {
        int a = 9;
        do {
            System.out.println("======================");
            System.out.printf("先执行do语句,在判断while,变量a的值为:%d%n", a);
            a = a + 1;
            System.out.printf("先执行do语句,在判断while,变量a的值为:%d%n", a);
        } while (a < 10);

    }
}

======================
先执行do语句,在判断while,变量a的值为:9
先执行do语句,在判断while,变量a的值为:10

二、while语句

public class AppMain {

    public static void main(String[] args) {
        int a  = 8;
        while (a < 10) {
            System.out.println("======================");
            System.out.printf("未加1前变量a的值为:%d%n", a);
            a = a + 1;
            System.out.printf("未加1前变量a的值为:%d%n", a);
        }
    }
}

======================
未加1前变量a的值为:8
未加1前变量a的值为:9
======================
未加1前变量a的值为:9
未加1前变量a的值为:10

三、for语句

public class AppMain {

    public static void main(String[] args) {
        int num = 1;
        for (int i = 8; i < 10; i++) {
            num = num + 1;
            System.out.printf("此时的num的值为:%d%n", num);
        }
    }
}

此时的num的值为:2
此时的num的值为:3


总结

do-while是语句会先执行do语句的逻辑代码块,再执行while里面的条件判断。也就是总是先执行一次。
while执行while里面的判断语句,在满足条件的情况下,执行逻辑代码块。
for循环,会先判断条件在进入循环
以上千万要注意死循环,一旦发生死循环,会造成内存溢出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值