秦疆的Java课程笔记:38 流程控制 while循环详解

发布时间 2023-11-27 16:50:37作者: Acolyte_9527
  • 循环结构:while循环,do...while循环,for循环

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

  • while事最基本的循环,结构为:

while(布尔表达式){
	//循环内容
}
  • 只要布尔表达式为true,循环就会一直执行下去。
  • 大多数情况下是会让循环停止下来的,西药一个让表达式失效的方式来结束循环。
public class WhileDemo1 {  
    public static void main(String[] args) {  
        //输出1-100  
        int i = 0;  
        while (i < 100){  
            i++;  
            System.out.println(i);  
        }  
    }  
}
========
效果略,总之是输出了从1-100
  • 少部分情况需要循环一直执行,比如服务器的请求响应监听等。
  • 循环条件一直为true就会造成无限循环,即“死循环”,正常的业务编程中应该尽量避免死循环。会影响程序性能或者造成程序卡死崩溃。
  • 死循环的伪代码示例。
public class WhileDemo2 {  
    public static void main(String[] args) {  
        //死循环  
        while (true){  
            //等待客户端连接  
            //定时检查:闹钟等  
            //.....  
        }  
    }  
}
  • 1+2+3+...+100=?
public class WhileDemo3 {  
    public static void main(String[] args) {  
        int i = 0;  
        int sum = 0;  
        while (i <= 100){  
            sum = sum + i;  
            i++;  
        }  
        System.out.println(sum);  
    }  
}
====结果====
5050