- while循环
- do…while循环
- for循环
- 在Java5中引入了一种主要用于数组的增强型for循环
while循环
- while循环是最基本的循环,它的结构为
while(布尔表达式){
//循环内容
}
- 只要布尔表达式为true,循环就会一直执行下去
- 我们大多数情况是会让循环停下来的,我们需要一个让表达失效的方式来结束循环
- 少部分情况需要循环一直执行,比如服务器的请求相应监听等
- 循环条件一直为true就会造成无限循环,我们正常的业务编程中应该尽量避免死循环,会影响程序性能或者造成程序卡死崩溃
代码
public class Main {
public static void main(String[] args) {
//输出0~100
int i = 0;
while (i<=100){
System.out.println(i);
i++;
}
}
}
运行结果正确
死循环
//死循环
public class Main {
public static void main(String[] args) {
while(true){
/*用途
等待客户端连接
定时检查
服务器的请求响应监听
*/
}
}
}
例题1
计算1+2+3+…+100?
代码
public class Main {
public static void main(String[] args) {
int i = 0;
int sum = 0;
while(i<=100){
sum = sum + i;
i++;
}
System.out.println(sum);
}
}
运行结果
5050
例题2
用while循环输出1-1000之间能被5整除的数,并且每行输出三个
代码
public class Main {
public static void main(String[] args) {
int i = 0;
while(i<=1000){
i++;
if (i%5==0){
System.out.