循环结构

发布时间 2023-07-25 16:33:49作者: 小安排

循环结构

-   while循环
-   do...while循环
-   for循环
-   for循环

-   在Java5中引入了一种主要用于数组的增强型for循环

while循环

-   while是最基本的循环,它的结构为
public class demo1 {
    public static void main(String[] args) {
        while(布尔表达式){
//            循环内容
        }
    }

}
-   只要布尔表达式为true,循环就会一直执行下去
-   我们大多数情况是会让循环停止下来,我们需要一个让表达式失效的方式来结束循环
-   少部分情况需要循环一直执行,比如服务器的请求响应监听等
-   循环条件一直为true就会造成无限循环(死循环),我们正常的业务编程中应该尽量避免死循环,会影响程序性能或者造成
程序卡死崩溃
-   思考:计算1+2+。。。100 = ?
public class demo1 {
    public static void main(String[] args) {
        int i = 0;
        int sum = 0;
        while(i <= 100){
//            循环内容
            sum = sum + i;
            i = i +1;
        }

        System.out.println(sum);
    }
}

do...while循环

-   对于while语句而言,如果不满足条件,则不能进入循环,但有时候我们需要即使不满足条件也至少执行一次
-   do...while循环和while循环相似,不同的是,do...while循环至少执行一次
do{}while(布尔表达式)
-   while和do...while的区别
    1 while先判断后执行,dowhile是先执行后判断
    2 dowhile总是保证循环体会被至少执行一次!这是他们的主要差别
public class demo1 {
    public static void main(String[] args) {
        int i = 0;
        int sum = 0;
        do{
            //  循环内容
            sum = sum + i;
            i = i +1;
        }while (i <= 100);

        System.out.println(sum);
    }
}
public class demo1 {
    public static void main(String[] args) {
        int a = 0;
        while (a <0){
            System.out.println(a);
            a++;
        }
        System.out.println("------------");
        do {
            System.out.println(a);
        }while (a < 0);
    }
}