第一部分:while循环基础
while循环是最基本的循环结构,先判断条件再执行循环体
学习目标
掌握while循环语法结构,理解条件判断与执行流程
1
基本语法结构
while循环的标准格式:
while (条件表达式) {
// 循环体代码
执行语句;
}
2
执行流程图
开始
⬇
判断条件
⬅
执行循环体
⬇
结束
3
简单计数示例
打印数字1到5:
public class WhileExample {
public static void main(String[] args) {
int count = 1;
while (count <= 5) {
System.out.println("当前数字: " + count);
count++; // 更新循环变量
}
}
}
4
输出结果
当前数字: 1
当前数字: 2
当前数字: 3
当前数字: 4
当前数字: 5
第二部分:do-while循环
do-while循环先执行一次循环体,再判断条件是否继续
1
基本语法结构
do {
// 循环体代码
执行语句;
} while (条件表达式);
注意:do-while循环至少执行一次循环体
2
与while循环的区别
特点 | while循环 | do-while循环 |
---|---|---|
条件判断时机 | 循环开始前 | 循环结束后 |
最少执行次数 | 0次(可能不执行) | 1次(至少执行一次) |
适用场景 | 先判断后执行 | 先执行后判断 |
3
实际应用示例
用户输入验证示例:
import java.util.Scanner;
public class DoWhileExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int password;
do {
System.out.print("请输入密码(1234): ");
password = scanner.nextInt();
} while (password != 1234);
System.out.println("密码正确,欢迎!");
scanner.close();
}
}
第三部分:常见错误与调试
识别并解决循环中的典型错误
错误1:无限循环
错误代码:
int i = 0;
while (i < 10) {
System.out.println(i);
// 忘记更新循环变量i
}
正确代码:
int i = 0;
while (i < 10) {
System.out.println(i);
i++; // 确保更新循环变量
}
错误2:边界条件错误
错误:少打印一个数
int count = 1;
while (count < 5) { // 应该 <= 5
System.out.println(count);
count++;
}
错误3:变量作用域问题
错误:变量声明位置错误
while (condition) {
int sum = 0; // 每次循环都重置为0
sum += value;
}
// sum在这里不可用
正确:变量声明在循环外
int sum = 0; // 声明在循环外
while (condition) {
sum += value;
}
// sum在这里可用
第四部分:进阶应用实例
实际项目中的循环应用场景
1
数字猜谜游戏
import java.util.Scanner;
import java.util.Random;
public class GuessNumberGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random();
int targetNumber = random.nextInt(100) + 1;
int guess;
int attempts = 0;
System.out.println("猜数字游戏!范围1-100");
do {
System.out.print("请输入你的猜测: ");
guess = input.nextInt();
attempts++;
if (guess < targetNumber) {
System.out.println("太小了!");
} else if (guess > targetNumber) {
System.out.println("太大了!");
}
} while (guess != targetNumber);
System.out.println("恭喜你!用了" + attempts + "次猜对了!");
input.close();
}
}
2
计算数字之和
public class SumCalculator {
public static void main(String[] args) {
int number = 12345;
int sum = 0;
int temp = number;
while (temp > 0) {
sum += temp % 10; // 获取个位数
temp /= 10; // 去掉个位数
}
System.out.println("数字" + number + "的各位之和: " + sum);
// 输出: 数字12345的各位之和: 15
}
}
第五部分:练习与总结
巩固知识并通过练习加深理解
基础练习题
- 使用while循环打印1到100的所有偶数
- 使用do-while循环实现简单的计算器程序(加减乘除)
- 编写程序找出100以内的所有质数
- 实现一个倒计时程序(从10数到1)
关键要点总结
- while循环:先判断后执行,可能一次都不执行
- do-while循环:先执行后判断,至少执行一次
- 确保循环条件最终会变为false,避免死循环
- 注意循环变量的初始化和更新
- break用于立即退出循环,continue跳过本次循环
最佳实践
- 循环变量命名要有意义(如count, index)
- 复杂循环考虑提取为独立方法
- 添加清晰的注释说明循环目的
- 避免在循环体内修改循环变量
- 使用增强for循环遍历集合(后面章节会讲)
在线练习
打开IDEA,创建新的Java类,尝试以下代码:
// 练习:打印九九乘法表
int i = 1;
while (i <= 9) {
int j = 1;
while (j <= i) {
System.out.print(j + "x" + i + "=" + (i*j) + "\t");
j++;
}
System.out.println();
i++;
}