package com.chenao.struct;
public class WhileDemo01 {
public static void main(String[] args) {
/*
1.只要布尔表达式为 true,循环就会一直执行下去
2.我们大多数情况是会让程序停止下来的,我们需要一个让表达式失效的方式来结束循环
3.少部分情况需要循环一直执行,比如服务器的请求响应监听等
4.循环条件一直为 true 就会造成无限循环【死循环】,我们正常的业务编程中应该尽量避免死循环
死循环会影响程序性能或者造成程序卡死崩溃
5.思考:计算1+2+3+...+100=?
*/
//循环结构:
/*
while(布尔表达式){
//循环内容
}
*/
//输出 1~100
int i = 0;
while (i<100){
i++;
System.out.println(i);
}
}
}
package com.chenao.struct;
public class WhileDemo02 {
public static void main(String[] args) {
//死循环 尽量避免死循环 影响程序性能、崩溃、卡死
while (true){
//等待客户端连接
//定时检查
}
}
}
package com.chenao.struct;
public class WhileDemo03 {
public static void main(String[] args) {
// 计算1+2+3+...+100=?
//高斯的故事
int i = 0;
int sum = 0;
while (i<=100){
sum = sum + i;
i++;
}
System.out.println(sum);
}
}
package com.chenao.struct;
public class WhileDemo04 {
public static void main(String[] args) {
//练习2:用 while 或 for 循环输出 1~1000 之间能被 5 整除的数,并且每行输出 3 个-
int i = 1;
while (i<=1000){
if (i%5==0){ //判断 i 是否能被 5 整除
System.out.print(i+"\t"); //如果能被 5 整除,输出,并空几格
}
if (i%(5*3)==0){ //如果输出了三个数,就可以换行
System.out.println();
}
i++; // i 自增
}
}
}
package com.chenao.struct;
public class WhileDemo05 {
public static void main(String[] args) {
//练习2:用 while 或 for 循环输出 1~1000 之间能被 5 整除的数,并且每行输出 3 个-
int i = 1;
int count = 0; //用于计算输出的个数,以便换行
while (i<=1000){
if (i%5==0){ //判断 i 是否能被 5 整除
System.out.print(i+"\t"); //如果能被 5 整除,输出,并空几格
count++;
}
i++; //自增
if (count%3==0){ //如果输出了三个数,就可以换行
System.out.println();
}
}
}
}