-
The complete format of the while loop:
初始化语句; while (条件判断语句) { 循环体语句; 条件控制语句; }
-
While loop execution process:
①Execute the initialization statement
②Execute the conditional judgment statement to see if the result is true or false
If it is false, the loop ends
If it is true, continue execution
③Execute loop body statement
④Execute conditional control statement
⑤Back to ②Continue
while loop case-Mount Everest
public class WhileTest {
public static void main(String[] args) {
//定义一个计数器,初始值为0
int count = 0;
//定义纸张厚度
double paper = 0.1;
//定义珠穆朗玛峰的高度
int zf = 8844430;
//因为要反复折叠,所以要使用循环,但是不知道折叠多少次,这种情况下更适合使用while循环
//折叠的过程中当纸张厚度大于珠峰就停止了,因此继续执行的要求是纸张厚度小于珠峰高度
while(paper <= zf) {
//循环的执行过程中每次纸张折叠,纸张的厚度要加倍
paper *= 2;
//在循环中执行累加,对应折叠了多少次
count++;
}
//打印计数器的值
System.out.println("需要折叠:" + count + "次");
}
}
Loop statement-dowhile loop
-
Full format:
初始化语句; do { 循环体语句; 条件控制语句; }while(条件判断语句);
-
Implementation process:
① Execute initialization statement
② Execute loop body statement
③ Execute conditional control statement
④ Execute the conditional judgment statement to see if the result is true or false
If it is false, the loop ends
If it is true, continue execution
⑤ Back to ② Continue
public class DoWhileDemo {
public static void main(String[] args) {
//需求:在控制台输出5次"HelloWorld"
//for循环实现
for(int i=1; i<=5; i++) {
System.out.println("HelloWorld");
}
System.out.println("--------");
//do...while循环实现
int j = 1;
do {
System.out.println("HelloWorld");
j++;
}while(j<=5);
}
}