1、循环:
——在满足循环条件下反复执行某一段代码,直到循环条件不被满足,否则一直进行下去,形成死循环。
——基本循环结构:
for循环,while循环,do ---- while循环
2、for循环结构:
——基本结构:
for(初始化语句;条件判断语句;条件控制语句){
循环体语句;
}
——利用for循环输出1-100;
public class ForTest01 {
public static void main(String[] args) {
//需求:输出数据1-100
for(int i=1; i<=100; i++) {
System.out.println(i);
}
System.out.println("--------");
//需求:输出数据100-1
for(int i=100; i>=1; i--) {
System.out.println(i);
}
}
}
3、While循环体
——基本格式:
初始化语句;
while(条件判断语句){
循环体语句;
条件控制语句;
},作用与for循环类似,可以相互转化。
——利用while打印5次HelloWorld
public class WhileDemo {
public static void main(String[] args) {
//需求:在控制台输出5次"HelloWorld"
//for循环实现
for(int i=1; i<=5; i++) {
System.out.println("HelloWorld");
}
System.out.println("--------");
//while循环实现
int j = 1;
while(j<=5) {
System.out.println("HelloWorld");
j++;
}
}
}
4、珠穆朗玛峰案例:
世界最高山峰是珠穆朗玛峰(8844.43米=8844430毫米),假如我有一张足够大的纸,它的厚度是0.1毫米。请问,我折叠多少次,可以折成珠穆朗玛峰的高度?
public class WhileTest{
public static void main(String[] args){
//定义一个计时器,初始值为0
int count = 0;
double paper = 0.1;
int zf = 8844430;
while(paper <= zf){
paper *= 2;
count++;
}
System.out.println("需要折叠"+count+"次");
//输出结果为27次
}
}