while循环语句格式:
- while循环的基本格式:
while(判断条件语句) {
循环体语句;
}
- 完整格式:
初始化语句;
while(判断条件语句) {
循环体语句;
控制条件语句;
}
执行流程:
1:执行初始化语句
2:执行判断条件语句,看其返回值是true还是false
如果是true,就继续执行循环体
如果是false,就结束循环
3:执行循环体语句;
4:执行控制条件语句
5:回到B继续。
执行流程图
需求:
统计”水仙花数”共有多少个
水仙花数:水仙花数是三位数,它的各位数字的立方和等于这个三位数本身,例如:370=33+73+00;371=33+73+13,370、371就是一个水仙花数
代码实现:
public class Demo07While { public static void main(String[] args) { int i = 100; int count = 0; //定义水仙花数的个数 while (i < 1000) { int b = i / 100; //取得百位数 int s = (i - 100 * b) / 10; //取得十位数 int g = (i - s * 10 - b * 100); //取得个位数 if (i == g * g * g + s * s * s + b * b * b) { //水仙花数判定 System.out.print(i + " "); //输出符合条件的数 count++; } i += 1; } System.out.println(); System.out.println("水仙花数总共有" + count + "个");//输出水仙花数的总数 } }
执行结果: