Appearance
7.2 while 循环
while 循环的概念
while 循环是 Java 中另一种常用的循环结构,它用于重复执行一段代码,直到条件不再满足。与 for 循环不同,while 循环更适合循环次数不确定的场景。
while 循环的语法
java
while (条件表达式) {
// 循环体:需要重复执行的代码
}- 条件表达式:每次循环开始前检查,返回布尔值,为 true 时执行循环体,为 false 时结束循环
- 循环体:需要重复执行的代码块
while 循环的执行流程
- 检查条件表达式:
- 如果为 true,执行循环体
- 如果为 false,结束循环
- 执行完循环体后,再次检查条件表达式
- 重复步骤 1-2,直到条件表达式为 false
while 循环的使用
基本用法
java
public class WhileLoopExample {
public static void main(String[] args) {
// 打印 1 到 5
int i = 1;
while (i <= 5) {
System.out.println("i = " + i);
i++;
}
}
}输出结果:
i = 1
i = 2
i = 3
i = 4
i = 5示例:计算 1 到 100 的和
java
public class SumExample {
public static void main(String[] args) {
int sum = 0;
int i = 1;
while (i <= 100) {
sum += i;
i++;
}
System.out.println("Sum of 1 to 100: " + sum);
}
}输出结果:
Sum of 1 to 100: 5050示例:猜数字游戏
java
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int secretNumber = 42;
int guess = 0;
System.out.println("Guess a number between 1 and 100:");
while (guess != secretNumber) {
System.out.print("Enter your guess: ");
guess = scanner.nextInt();
if (guess < secretNumber) {
System.out.println("Too low!");
} else if (guess > secretNumber) {
System.out.println("Too high!");
} else {
System.out.println("Congratulations! You guessed the number.");
}
}
scanner.close();
}
}示例:读取用户输入直到输入特定值
java
import java.util.Scanner;
public class ReadInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = "";
System.out.println("Enter 'exit' to quit:");
while (!input.equals("exit")) {
System.out.print("Enter something: ");
input = scanner.nextLine();
System.out.println("You entered: " + input);
}
System.out.println("Goodbye!");
scanner.close();
}
}while 循环的应用场景
1. 不确定次数的循环
java
// 读取用户输入直到输入正确
Scanner scanner = new Scanner(System.in);
int age = -1;
while (age < 0 || age > 120) {
System.out.print("Enter your age: ");
age = scanner.nextInt();
if (age < 0 || age > 120) {
System.out.println("Invalid age. Please try again.");
}
}
System.out.println("Your age is: " + age);2. 基于条件的循环
java
// 计算一个数的阶乘
int n = 5;
int factorial = 1;
int i = 1;
while (i <= n) {
factorial *= i;
i++;
}
System.out.println(n + "! = " + factorial);3. 无限循环
java
// 无限循环,需要在循环体中使用 break 语句退出
while (true) {
System.out.println("Press Ctrl+C to exit");
// 执行一些操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}示例:while 循环的使用
java
public class WhileLoopApplication {
public static void main(String[] args) {
// 计算斐波那契数列的前 10 项
System.out.println("Fibonacci Sequence:");
int a = 0, b = 1;
int count = 2;
System.out.print(a + " " + b + " ");
while (count < 10) {
int c = a + b;
System.out.print(c + " ");
a = b;
b = c;
count++;
}
System.out.println();
// 寻找第一个大于 1000 的 2 的幂
System.out.println("\nFirst power of 2 greater than 1000:");
int power = 1;
while (power <= 1000) {
power *= 2;
}
System.out.println(power);
// 计算 1 到 n 的和,直到和大于 100
System.out.println("\nSum of numbers until sum > 100:");
int sum = 0;
int i = 1;
while (sum <= 100) {
sum += i;
i++;
}
System.out.println("Sum: " + sum);
System.out.println("Last number added: " + (i - 1));
}
}常见问题
1. 死循环
症状:循环永远不会结束
解决方案:确保循环条件最终会变为 false,或在循环体中使用 break 语句
2. 循环变量未更新
症状:循环变量没有在循环体中更新,导致死循环
解决方案:确保在循环体中更新循环变量
3. 条件表达式错误
症状:循环次数不符合预期
解决方案:仔细检查条件表达式,确保它能够在适当的时候变为 false
4. 初始条件不满足
症状:循环体一次也不执行
解决方案:确保循环的初始条件是正确的
while 循环与 for 循环的比较
| 特性 | while 循环 | for 循环 |
|---|---|---|
| 语法 | 简洁,只有条件表达式 | 更结构化,包含初始化和更新表达式 |
| 适用场景 | 循环次数不确定 | 循环次数确定 |
| 变量作用域 | 循环变量在循环外声明,作用域更大 | 循环变量在循环内声明,作用域局限于循环 |
| 可读性 | 对于简单循环,可读性好 | 对于复杂循环,结构更清晰 |
总结
while 循环是 Java 中常用的循环结构之一,它适用于循环次数不确定的场景。while 循环的语法简洁,执行流程清晰。
在使用 while 循环时,需要注意:
- 条件表达式的正确设置
- 循环变量的更新
- 避免死循环
- 确保循环体的逻辑正确性
通过合理使用 while 循环,可以处理各种需要重复执行的任务,提高程序的灵活性和可读性。
