while(判断条件语句){
循环体语句;
}
2、拓展格式
初始化语句;
while(判断条件语句){
循环体语句;
控制条件语句;
}
这货为啥有两种格式?
对不起,我现在还不知道,总之请大家重点记住扩展格式。
但话说回来,这么看上去,while语句和for语句的格式长得很像,不知道他俩的功能是否可以等价转换。
(二)执行流程①执行初始化语句;
②执行判断条件语句,看结果是true还是false;(true执行,false结束循环)
③执行循环体语句;
④执行控制条件语句;
⑤回到第②条继续。
为了方便大家观赏(主要还是因为我懒),还是沿用输出10次hello world的例子哈。
for语句是这样写的:
public class demon {
public static void main(String[] args) {
for (int x =1; x < 10; x++) {
System.out.println("hello world");
}
}
}
而while语句则写成这样:
public class demon {
public static void main(String[] args) {
int x=1;
while (x<10) {
System.out.println("hello world");
x++;
}
}
}
有啥区别?
好像也没什么本质不同,除了语句的位置变了以外,其他该有啥还有啥。
区别肯定是有滴,否则就不会分成两种了,小同志们不要着急,下面我们慢慢总结。
(三)while语句和for语句的区别区别1、
控制条件语句所控制的变量,在for循环结束后,就不能再被访问了,而while循环结束后还可以访问。这是因为,for循环结束后,该变量就从内存中消失,能够提高内存使用率。
啥意思?
用for循环:
public class demon {
public static void main(String[] args) {
for (int x=0;x<5;x++) {
System.out.println(x);
}
}
}
0 1 2 3 4 Process finished with exit code 0
可如果我写成下面这样,就会报错:
public class demon {
public static void main(String[] args) {
for (int x=0;x<5;x++) {
}
System.out.println(x);
}
}
java: 找不到符号 符号: 变量 x 位置: 类 demon
没看懂这俩例子区别的小伙伴,注意一下System.out.println(x)出现的位置。
在这个例子中,变量x的范围,局限在:
for (int x=0;x<5;x++) {
}
这个大括号里,当你跳出范围,访问变量x时,系统就会报错。如果你非要继续访问,就可以使用while语句来实现,比如下面这样写:
public class demon {
public static void main(String[] args) {
int x=0;
while (x<5) {
x++;
}
System.out.println(x);
}
}
因为这里的变量x的势力范围,包含在:
public static void main(String[] args) {
}
这个大括号里。
区别2、
for循环语句针对有明确范围的判断进行操作,比如从1-100之间;
while循环语句,适合判断次数不明确的操作,比如吃葡萄,你肯定不会去数数(数5颗吃一次),只要有就吃(只要葡萄还有,管它有多少颗,甩开腮帮子吃哇)。
这里我们就不举例了,感兴趣的小伙伴们,可以自己试着用while语句改写一下前面用for语句编写的代码哈。
(四)经典案例来看一道题:
珠穆朗玛峰高8848m,现在用一张足够大的纸,厚度为0.01m。请问折叠多少次,就可以保证厚度不低于珠峰的高度?
分析一下:
①、8848m相当于限制了最大范围,0.01m则限制了最小值;
②、每折叠一次,这张纸的厚度都相当于之前的两倍,也就是*=2;
③、由于8848和0.01一个是整数,一个是小数,为了防止精度损失,可以将他们同时扩大100倍,即884800和1。
所以这道题的代码可以写成:
public class demon {
public static void main(String[] args) {
int count=0;//定义一个统计变量;
int paper=1;//一张纸的厚度;
int max=884800;//最大值不能超过珠峰高度;
while (paper
总共需要折叠:20次
Process finished with exit code 0
当然如果你同时也想知道,每一次折叠后纸张的厚度的话,那么也可以写成这样:
public class demon {
public static void main(String[] args) {
int count=0;//定义一个统计变量;
int paper=1;//一张纸的厚度;
int max=884800;//最大值不能超过珠峰高度;
while (paper
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
131072
262144
524288
1048576
总共需要折叠:20次
Process finished with exit code 0
文字部分图片来自网络,侵权立删



