while循环
while是最基本的循环,它的结构为:
while(布尔表达式){ //循环内容 }
- 只要布尔表达式为true,循环就会一直执行下去。
- 我们大多数情况是会让循环停止下来的,我们需要一个让表达式失效的方式来结束循环。
- 少部分情况需要循环一直执行,比如服务器的请求响应监听等。
- 循环条件一直为true就会造成无限循环【死循环】。我们正常的业务编程中应该尽量避免死循环。会影响程序性能或者造成程序卡死奔溃!
Demo01
代码
package struct;
public class WhileDemo01 {
public static void main(String[] args) {
int i = 0;
while (i<100){
i++;
System.out.println(i);
}
}
}
运行结果
1
2
3
4
.
.
.
100
Demo02
- 死循环‘
代码
package struct;
public class WhileDemo02 {
public static void main(String[] args) {
//死循环
while (true){
//等待客户端连接
//定时检查
//........
}
}
}
运行结果
//程序会一直运行下去,直到程序奔溃or没电
Demo03
计算1+2+3+...+100=?
代码
package struct;
public class WhileDemo03 {
public static void main(String[] args) {
//思考:计算1+2+3+...+100=?
int i = 0;
int num = 0;
while (i<=100){
num = num +i;
i++;
}
System.out.println(num);
}
}
运行结果
5050