Demo
while循环:
语句定义格式1:
初始化条件语句;
while(判断条件语句){
循环体语句;
控制条件语句;
}
语句定义格式2:
初始化条件语句;
do{
循环体语句;
控制条件语句;
}while(判断条件语句);
注意:
1、while循环可以和for循环等价转换
2、for循环和while循环的使用场景:
for循环适合明确的范围内循环 【吃葡萄🍇】
当循环次数不明确获取就是要求次数的时候,优先考虑while循环【喝水】
public class WhileDemo1 {
public static void main(String[] args) {
for (int i = 1; i < 0; i++) {
System.out.println("hello world");
}
System.out.println("---------------------------");
int i = 1;
while (i < 0){
System.out.println("hello world");
i++;
}
System.out.println("---------------------------");
int i2 = 1;
do{
System.out.println("hello world");
i2++;
}while (i2 < 0);
}
}
Test
public class WhileTest1 {
public static void main(String[] args) {
int high = 884800;
int thickness = 1;
int count = 0;
while (thickness<high){
thickness *=2;
count++;
}
System.out.println("共折叠 "+count+"次");
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步