While循环

循环结构

  • while循环

  • do...while循环

  • for循环

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

while 循环

  • while是最基本的循环,它的结构为:
while( 布尔表达式 ) {
    //循环内容
}
package com.yue.struct;

public class WhileDemo02 {
    public static void main(String[] args) {
        while(true){
            //等待客户端连接
            //定时检查
            //。。。。。。
        }
    }
}
  • 只要布尔表达式为 true ,循环就会一直执行下去。
  • 我们大多数情况会让循环停止下来的,我们需要一个让表达式失效的方式来结束循环。
  • 少部分情况需要循环一直执行,比如服务器的请求响应监听等。
  • 循环条件一直为true就会造成问无限循环【死循环】,我们正常业务编程中应该尽量避免死循环。会影响程序性能或者程序卡死崩溃!
  • 思考:计算1+2+3+...+100=?
package com.yue.struct;

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

        //输出1~100

        int i = 0;

        while(i<100){
            i++;
            System.out.println(i);
        }

    }
}
posted @ 2023-03-08 20:25  yuexingjian  阅读(12)  评论(0编辑  收藏  举报