Java语言基础(七) : 循环结构之 while 循环

时间:2022-12-13 13:40:49

while循环的语法格式:

        while(判断条件语句) {
循环体语句;
}

扩展格式:

        初始化语句;
while(判断条件语句) {
循环体语句;
控制条件语句;
}


通过这个格式,我们就可以看到其实和for循环是差不多的。
for(初始化语句;判断条件语句;控制条件语句) {
循环体语句;
}

下面通过代码来演示while循环:

public class WhileDemo01 {
public static void main(String[] args) {
//输出10次"HelloWorld"
//for语句版
for(int x=0; x<10; x++) {
System.out.println("HelloWorld");
}
System.out.println("--------------");
//while语句版
int x=0;
while(x<10) {
System.out.println("HelloWorld");
x++;
}
}
}

初始化语句:

    while(判断条件语句) {
循环体语句;
控制条件语句;
}

for(初始化语句;判断条件语句;控制条件语句) {
循环体语句;
}

案例1:用while循环实现:
(1)求出1-100之和
(2)统计水仙花数有多少个

public class WhileDemo02 {
public static void main(String[] args) {
//求出1-100之和
//for语句版本
int sum = 0;

for(int x=1; x<=100; x++) {
sum+=x;
}

System.out.println("sum:"+sum);
System.out.println("--------");
//while语句版本
int sum2 = 0;

int y=1;
while(y<=100) {
sum2+=y;
y++;
}

System.out.println("sum2:"+sum2);
System.out.println("--------");
}
}

public class WhileDemo03 {
public static void main(String[] args) {
//for循环版本
int count = 0;

for(int x=100; x<1000; x++) {
int ge = x%10;
int shi = x/10%10;
int bai = x/10/10%10;

if((ge*ge*ge+shi*shi*shi+bai*bai*bai) == x) {
count++;
}
}
System.out.println("count:"+count);
System.out.println("------------");

//while循环版本
int count2 = 0;
int y = 100;
while(y<1000) {
int ge = y%10;
int shi = y/10%10;
int bai = y/10/10%10;
if((ge*ge*ge+shi*shi*shi+bai*bai*bai) == y) {
count2++;
}

y++;
}

System.out.println("count2:"+count2);
}
}

while循环和for循环的区别?

使用区别:
如果你想在循环结束后,继续使用控制条件的那个变量,用while循环,否则用for循环。不知道用for循环。因为变量及早的从内存中消失,可以提高内存的使用效率。
其实还有一种场景的理解:
如果是一个范围的,用for循环非常明确。如果是不明确要做多少次,用while循环较为合适。举例:吃葡萄。
看如下代码:

public class WhileDemo04 {
public static void main(String[] args) {
//for循环实现
for(int x=0; x<10; x++) {
System.out.println("我爱学习Java!");
}
//这里不能在继续访问了
//System.out.println(x);

//while循环实现
int y = 0;
while(y<10) {
System.out.println("我爱学习Java!");
y++;
}
//这里是可以继续访问的
System.out.println(y);
}
}

我们再来看一个需求案例:
我国最高山峰是珠穆朗玛峰:8848m,我现在有一张足够大的纸张,厚度为:0.01m。
请问,我折叠多少次,就可以保证厚度不低于珠穆朗玛峰的高度?
分析:
A:定义一个统计变量,默认值是0
B:最高山峰是珠穆朗玛峰:8848m这是最终的厚度。
我现在有一张足够大的纸张,厚度为:0.01m这是初始厚度
C:我折叠多少次,就可以保证厚度不低于珠穆朗玛峰的高度?
折叠一次有什么变化呢?就是厚度是以前的2倍。
D:只要每次变化的厚度没有超过珠穆朗玛峰的高度,就折叠,统计变量++
E:输出统计变量。
我写的代码:

public class WhileDemo05 {
public static void main(String[] args) {
//定义一个统计变量,默认值是0
int count = 0;
//最高山峰是珠穆朗玛峰:8848m这是最终的厚度
//我现在有一张足够大的纸张,厚度为:0.01m这是初始厚度
//为了简单,我把0.01变成1,同理8848就变成了884800
int end = 884800;
int start = 1;
while(start<end) {
//只要每次变化的厚度没有超过珠穆朗玛峰的高度,就折叠,统计变量++
count++;
//折叠一次有什么变化呢?就是厚度是以前的2倍。
start *= 2;
System.out.println("第"+count+"次厚度是"+start);
}
//输出统计变量。
System.out.println("要叠"+count+"次");
}
}