目录
1. for循环案例:每行打印2个水仙花数
// 水仙花数是一个三位数
// 水仙花数的每一位数的三次方相加,最后的结果等于这个数本身
public class ForDemo{
public static void main(String[] args){
int count = 0;
for(int i=100;i<1000;i++){
int ge = i%10;
int shi = i/10%10;
int bai = i/10/10%10;
if(ge*ge*ge+shi*shi*shi+bai*bai*bai==i) {
System.out.print(i+" ");
count++;
if(count%2==0) System.out.println();
}
/* 放在第一个if外面会出现0%2情况
if(count%2==0){
System.out.println();
}
*/
}
}
}
2. while循环案例:珠穆朗玛峰
/*
需求:世界最高山峰是珠穆朗玛峰(8844.43米=8844430毫米),
假如我有一张足够大的纸,它的厚度是0.1毫米。
请问,我折叠多少次,可以折成珠穆朗玛峰的高度?
*/
public class WhileDemo{
public static void main(String[] args){
double height = 0.1;
int count = 0;
while(height<8844430){
height *= 2;
count++;
}
System.out.println("需要折叠"+count+"次");
}
}
3. do while循环案例:打扫卫生
// 需求:打扫卫生,检查合格之后结束
import java.util.Scanner;
public class DoWhileDemo{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int count = 0;
do{
count++;
System.out.println("打扫了"+count+"次");
System.out.println("卫生检查中。。。");
boolean result = sc.nextBoolean();//键盘输入卫生检查结果
}while(!result);
System.out.println("卫生检查通过,回家吃饭去吧!!");
}
}
4. 三种循环的区别
-
for、while循环: 必须满足条件才执行。
-
do...while:不管条件是否成立,循环语句体至少执行一次。
-
for循环:控制循环的变量通常是在for语句中定义、初始化,所以只能在循环里面使用。
-
while循环:控制循环的变量一般都是循环外定义、初始化,所以可以在循环外面使用。
-
循环开始前,知道次数,使用for循环;循环开始前,不知道次数,使用while;循环do...while很少使用。
如有错误欢迎留言评论,及时更正。 羽露风 5月9日