Control Structures II: Repetition (Part 1) 控制结构二:循环结构(上)
Learning Objectives 学习目标
- Explain the operational differences between pre-test (while) and post-test (do-while) loops.
- Implement sentinel-controlled loops to accumulate user values until an exit flag is entered.
- Create interactive applications matching retail transaction logic.
- 解释前测循环 (while) 和后测循环 (do-while) 之间的操作差异。
- 实现哨兵控制的循环,以累加用户输入值,直到输入退出标志。
- 创建符合零售交易逻辑的交互式应用程序。
2 · Pre-test Loops (while)
A pre-test loop evaluates its boolean expression before executing the loop body. If the condition is initially false, the loop body never executes. In Java, this is represented by the while loop:
前测循环在执行循环体之前评估其布尔表达式。如果条件最初为假,则循环体永远不会执行。在 Java 中,这由 while 循环表示:
int count = 0; while (count < 5) {{ System.out.println("Count: " + count); count++; }}
3 · Post-test Loops (do-while)
A post-test loop executes its loop body first, and then evaluates the condition. Consequently, the loop body is guaranteed to execute at least once. In Java, this is represented by the do-while loop:
后测循环先执行其循环体,然后再评估条件。因此,循环体保证至少执行一次。在 Java 中,这由 do-while 循环表示:
int val = 10; do {{ System.out.println("Value: " + val); val++; }} while (val < 5); // Condition is false, but prints once
4 · Sentinel-Controlled Loops
In many cases, the exact number of loop iterations is not known in advance. A sentinel-controlled loop reads inputs continuously until a special value (called a sentinel, e.g., -1 or 0) is entered, signaling the end of input data.
在许多情况下,循环的精确执行次数是无法提前获知的。哨兵控制循环会持续读取输入,直到用户输入一个特殊值(称为哨兵,例如 -1 或 0),这标志着输入数据的结束。
Applied Case Study: Order Price Accumulator应用案例研究:订单价格累加器
Company: Kompas Order Registry.
We write an interactive program that prompts cashiers for product prices sequentially. If they enter -1, the loop terminates, and the system prints the aggregated total.
公司: Kompas Order Registry。
我们编写一个交互式程序,按顺序提示收银员输入商品价格。如果输入 -1,则循环终止,系统打印累计总额。
Loop Type Comparison循环类型比较
| Loop Type循环类型 | Check Point检查点位置 | Minimum Executions最少执行次数 | Common Use Case常见用途 |
|---|---|---|---|
| while | Pre-test (Before body)前测(进入循环体前) | 0 | Reading files, sentinel input读取文件、哨兵输入 |
| do-while | Post-test (After body)后测(执行循环体后) | 1 | Menu selection, data validation菜单选择、数据验证 |
Order Accumulator Source Code订单累加器程序源代码
import java.util.Scanner; public class OrderAccumulator {{ public static void main(String[] args) {{ Scanner input = new Scanner(System.in); double total = 0.0; double price = 0.0; System.out.println("Enter item prices (enter -1 to finish):"); System.out.print("Enter price RM: "); price = input.nextDouble(); while (price != -1.0) {{ total += price; System.out.print("Enter price RM: "); price = input.nextDouble(); }} System.out.printf("Total accumulated price: RM %.2f%n", total); input.close(); }} }}
💡 Hint / 提示
We read the first value before entering the loop. This pattern (priming read) prevents using sentinel value -1 in arithmetic calculations.我们在进入循环之前读取第一个数值。这种模式(引导读取)可防止在算术计算中使用哨兵值 -1。
✅ Show Expected Console Flow / 显示预期控制台运行
Enter item prices (enter -1 to finish): Enter price RM: 15.50 Enter price RM: 24.00 Enter price RM: 8.50 Enter price RM: -1 Total accumulated price: RM 48.00
Check Your Understanding自我检测
Q1. What is the minimum number of times a do-while loop executes?do-while 循环最少执行多少次?
Q2. In sentinel-controlled loops, why is a priming read input used?在哨兵控制的循环中,为什么要使用引导读取输入?
Q3. If a while loop condition checks: while (count < 0) and count = 5, how many times will it run?如果 while 循环条件检查:while (count < 0) 且 count = 5,它会运行多少次?