前言
`
循环结构语句包括do-while或者while以及for循环
一、do-while语句
public class AppMain {
public static void main(String[] args) {
int a = 9;
do {
System.out.println("======================");
System.out.printf("先执行do语句,在判断while,变量a的值为:%d%n", a);
a = a + 1;
System.out.printf("先执行do语句,在判断while,变量a的值为:%d%n", a);
} while (a < 10);
}
}
======================
先执行do语句,在判断while,变量a的值为:9
先执行do语句,在判断while,变量a的值为:10
二、while语句
public class AppMain {
public static void main(String[] args) {
int a = 8;
while (a < 10) {
System.out.println("======================");
System.out.printf("未加1前变量a的值为:%d%n", a);
a = a + 1;
System.out.printf("未加1前变量a的值为:%d%n", a);
}
}
}
======================
未加1前变量a的值为:8
未加1前变量a的值为:9
======================
未加1前变量a的值为:9
未加1前变量a的值为:10
三、for语句
public class AppMain {
public static void main(String[] args) {
int num = 1;
for (int i = 8; i < 10; i++) {
num = num + 1;
System.out.printf("此时的num的值为:%d%n", num);
}
}
}
此时的num的值为:2
此时的num的值为:3
总结
do-while是语句会先执行do语句的逻辑代码块,再执行while里面的条件判断。也就是总是先执行一次。
while执行while里面的判断语句,在满足条件的情况下,执行逻辑代码块。
for循环,会先判断条件在进入循环
以上千万要注意死循环,一旦发生死循环,会造成内存溢出。
本文详细介绍了Java中的do-while、while和for三种循环语句的工作原理,强调了do-while总是先执行一次的特点,while的条件判断后再执行,以及for循环的条件判断前置。同时提醒注意避免死循环导致的内存溢出问题。

被折叠的 条评论
为什么被折叠?



