java程序设计开发,循环结构(for、while)
学习目标:
-
掌握
for
和while
循环的语法与使用场景 -
能够通过循环解决重复性任务
-
理解循环控制语句(
break
、continue
) -
避免无限循环并优化代码逻辑
一、课程引入
1.1 为什么需要循环?
-
生活场景:
-
重复打印100份文件 → 循环执行打印操作
-
统计全班学生成绩 → 循环遍历每个学生的分数
-
-
核心作用:减少重复代码,提高效率
1.2 循环的分类
-
for
循环:明确循环次数时使用(如遍历数组) -
while
循环:不确定循环次数时使用(如用户输入验证) -
do-while
循环:至少执行一次循环体
二、for循环
2.1 基本语法
for (初始化; 循环条件; 迭代操作) {
// 循环体
}
案例1:打印1~100的偶数
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) {
System.out.print(i + " ");
}
}
2.2 嵌套循环
案例2:打印九九乘法表
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + "×" + i + "=" + (i*j) + "\t");
}
System.out.println();
}
2.3 常见错误
-
错误1:循环条件永真导致无限循环
for (int i = 0; i >= 0; i++) { // 无限循环 System.out.println(i); }
错误2:循环变量作用域问题
for (int i = 0; i < 10; i++); // 分号导致循环体为空
System.out.println(i); // 编译错误:i未定义
三、while与do-while循环
3.1 while循环
语法
while (循环条件) {
// 循环体
}
案例3:用户密码验证
Scanner scanner = new Scanner(System.in);
String password;
boolean isCorrect = false;
while (!isCorrect) {
System.out.print("请输入密码:");
password = scanner.nextLine();
isCorrect = password.equals("123456");
}
System.out.println("密码正确!");
3.2 do-while循环
语法
do {
// 循环体
} while (循环条件);
案例4:至少执行一次的游戏菜单
int choice;
do {
System.out.println("1.开始游戏 2.退出");
choice = scanner.nextInt();
} while (choice != 1 && choice != 2);
四、循环控制语句
4.1 break与continue
语句 | 作用 | 示例 |
---|---|---|
break | 终止整个循环 | 找到目标后立即退出循环 |
continue | 跳过本次循环剩余代码 | 跳过奇数的处理 |
案例5:查找第一个能被7整除的数
for (int i = 1; i <= 100; i++) {
if (i % 7 == 0) {
System.out.println("找到:" + i);
break; // 找到后立即终止循环
}
}
案例6:跳过负数的累加
int sum = 0;
for (int num : numbers) {
if (num < 0) {
continue; // 跳过负数
}
sum += num;
}
五、综合应用与优化
5.1 综合案例
案例7:统计学生成绩分布
int[] scores = {85, 92, 45, 78, 60};
int countA = 0, countB = 0, countC = 0;
for (int score : scores) {
if (score >= 90) {
countA++;
} else if (score >= 60) {
countB++;
} else {
countC++;
}
}
System.out.println("A:" + countA + " B:" + countB + " C:" + countC);
案例8:模拟抽奖系统
Random random = new Random();
int target = random.nextInt(10) + 1;
int guess;
int attempts = 0;
while (true) {
System.out.print("猜数字(1-10):");
guess = scanner.nextInt();
attempts++;
if (guess == target) {
System.out.println("恭喜!用了" + attempts + "次");
break;
}
}
5.2 循环优化技巧
-
减少循环内部计算:将不变的计算提到循环外
// 优化前
for (int i = 0; i < list.size(); i++) { ... }
// 优化后
int size = list.size();
for (int i = 0; i < size; i++) { ... }
六、总结与练习
6.1 总结
-
循环选择:
-
已知次数 →
for
-
未知次数 →
while
或do-while
-
-
避免死循环:确保循环条件能变为
false
6.2 课后任务
-
编写程序输出100以内的所有质数
-
使用
while
循环模拟ATM取款流程(输入金额,余额不足时提示) -
预习下一节课:数组与集合
6.3 扩展挑战
-
用循环打印菱形图案(根据用户输入的行数动态生成)