while循环
基本语法
循环结构四要素
:
- 初始化部分
- 循环条件部分
- 循环体部分
- 迭代部分
语法格式:
①初始化部分
while(②循环条件部分){
③循环体部分;
④迭代部分;
}
**执行过程:**①-②-③-④-②-③-④-②-③-④-…-②
图示:
说明:
- while(循环条件)中循环条件必须是boolean类型
- 注意不要忘记声明④迭代部分。否则,循环将不能结束,变成死循环
- for循环和while循环可以互相替换。二者没有性能上的差别。实际开发中,根据具体结构的情况,选择哪个格式更合适、美观
- for循环和while循环的区别:初始化条件部分的作用域范围不同
应用举例
**案例1:**输出5行HelloWorld!
class WhileTest1{
public static void main(String[] args){
int i = 0;
while(i<5){
System.out.println("Hello World");
i++;
}
}
}
**案例2:**遍历1-100的偶数,并计算所有偶数的和、偶数的个数(累加的思想)
class WhileTest2{
public static void main(String[] args){
int i = 1;
int count = 0;
int sum = 0;
while(i<=100){
if(i%2==0){
System.out.println(i);
count++;
sum += i;
}
i++;
}
System.out.println("偶数的总和为:" + sum);
System.out.println("偶数的个数为:" + count);
}
}
**案例3:**猜数字游戏
随机生成一个100以内的数,猜这个随机数是多少?
从键盘输入数,如果大了,提示大了;如果小了,提示小了;如果对了,就不再猜了,并统计一共猜了多少次。
提示:生成一个[a,b] 范围的随机数的方式:(int)(Math.random() * (b - a + 1) + a)
import java.util.Scanner;
public class WhileTest3{
public static void main(String[] args){
int random = (int)(Math.random()*100);
System.out.println("随机数为"+random);
Scanner scan = new Scanner(System.in);
System.out.print("请输入猜测的数字:");
int guess = scan.nextInt();
int count = 1;
while(guess != random){
if(guess > random){
System.out.println("猜大了");
}else{
System.out.println("猜小了");
}
System.out.print("请重新猜测数字:");
guess = scan.nextInt();
count++;
}
System.out.println("恭喜你,猜对了");
System.out.println("一共猜了"+count+"次");
}
}
案例4:折纸珠穆朗玛峰
世界最高山峰是珠穆朗玛峰,它的高度是8848.86米,假如我有一张足够大的纸,它的厚度是0.1毫米。
请问,我折叠多少次,可以折成珠穆朗玛峰的高度?
public class WhileTest4{
public static void main(String[] args){
double zhu = 8848.86 * 1000;
int count = 0;
double zhi = 0.1;
while(zhi <= zhu){
zhi *= 2;
count++;
}
System.out.println(zhi);
System.out.println(count);
}
}
**练习:**从键盘输入整数,输入0结束,统计输入的正数、负数的个数。
import java.util.Scanner;
public class WhileTest5{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("请输入一个整数:");
int m = scan.nextInt();
int count = 1;
while(m!=0){
System.out.print("请输入一个整数:");
m =scan.nextInt();
count++;
}
System.out.println(count);
}
}