While循环
- while循环语句格式
初始化语句;
while(判断条件语句){
循环体语句;
控制条件语句;
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-g2wk0Rcp-1612262454173)(C:\Users\87370\AppData\Roaming\Typora\typora-user-images\image-20210202162308717.png)]
- 输出十遍HelloWorld
/**
* while循环
* 语句格式:
* 初始化语句;
* while(条件判读){
* 循环体语句;
* 控制条件语句;
* }
* for循环:
* 语句格式:
* for(初始化语句;判断条件;控制条件语句){
* 循环体语句
* }
*
*/
public class WhileDemo01 {
public static void main(String[] args) {
//输出十遍"HelloWorld"
int num = 1;
while (num<=10){
System.out.print("第"+num+"遍"+"\t");
System.out.println("HelloWorld");
num++;
}
}
}
- 使用While语句输出水仙花数
public class WhileDemo02 {
public static void main(String[] args) {
int num = 100;
while(num<=999){
int g = (num/1)%10;
int s = (num/10)%10;
int b = (num/100)%10;
if ((g*g*g)+(s*s*s)+(b*b*b)==num){
System.out.println(num);
}
num++;
}
}
}
-
for循环和while循环的区别
- 控制条件语句的变量,作用域不同
for:在循环体内有效
while:在主方法内有效
- for循环:针对一个范围
while循环:适合循环次数不明确的操作
public class WhileDemo03 {
public static void main(String[] args) {
//for
for (int i = 1;i<=10;i++){
System.out.println(i+"好好学习");
}
//while
int j = 1;
while(j<=10){
System.out.println(j+"好好学习");
j++;
}
}
}
- 一张纸,最多对折9次,超过30次,其总厚度将超过10个珠穆朗玛峰假如一张纸厚0.01m,对折多少次将超过珠穆朗玛峰(8848m)
public class WhileDemo04 {
public static void main(String[] args) {
int num = 0;
double h = 0.01;
while (h<=8848){
h = h*2;
num++;
System.out.println("第"+num+"次"+h);
}
System.out.println(num);
}
}