Day14--while循环

xiaokunzhong / 2024-10-11 / 原文

Day14--while循环

三种循环结构。

while 循环、do...while 循环、for 循环。

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

while循环

while 是最基本的循环,它的结构为:

while (布尔表达式){
// 循环内容
}

只要布尔表达式为 true,循环就会一直执行下去。

我们大多数情况是会让循环停止下来的,我们需要个让表达式失效的方式来结束循环。

少部分情况需要循环一直执行,比如服务器的请求响应监听等。

循环条件一直为 true 就会造成无限循环【死循环】,我们正常的业务编程中应该尽量避免死循环,会影响程序性能或者造成程序卡死崩溃!

思考:计算 1+2+3+...+100=?

实例1:输出1~10

//输出1~10
        int i=0;

        while(i<10){
            i++;
            System.out.println(i);
        }
        /*
        输出结果:
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
         */

实例2:计算 1+2+3+...+100=?

错误:

package com.liu.www.struct;

public class WhileDemo03 {
    public static void main(String[] args) {
        int i=0;
        int sum=0;
        while (i<100){
            i++;
            sum=sum+i;
        }
    }
    System.out.println(sum);
}

错误原因:

System.out.println(sum);这行代码放置的位置错误。Java 中,方法体中的可执行语句必须放在方法内部的花括号内,不能直接放在类中。

正确代码:

package com.liu.www.struct;

public class WhileDemo03 {
    public static void main(String[] args) {
        int i = 0;
        int sum = 0;
        while (i < 100) {
            i++;
            sum = sum + i;
        }
        System.out.println(sum);
    }
}