循环就像城市交通管理系统,不同类型的循环好比各种交通指挥方式:for循环像定时红绿灯,while循环像交警手动指挥,do-while则像必须至少放行一次的应急通道。
想象一个自助餐厅的运营场景:
- for循环:像固定菜品的取餐区,知道确切数量(比如10道热菜)
- while循环:像现做档口,只要还有客人排队就继续供应
- do-while循环:像必须至少询问一次的会员卡办理
这种综合应用场景,最能体现循环在实际开发中的价值。
案例解析
智能点餐系统
编写程序,结合多种循环实现餐厅管理系统。
# 源文件保存为“SmartRestaurant.java”
import java.util.Scanner;
public class SmartRestaurant {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] menu = {
"红烧肉", "清蒸鱼", "宫保鸡丁", "麻婆豆腐"};
int[] prices = {
58, 88, 42, 36};
int[] orders = new int[menu.length];
int total = 0;
// for循环展示固定菜单
System.out.println("=== 今日菜单 ===");
for(int i=0; i<menu.length; i++) {
System.out.printf("%d. %s %d元\n", i+1, menu[i], prices[i]);
}
// while循环处理点餐
boolean ordering = true;
while(ordering) {
System.out.print("\n请输入菜品编号(0结束):");
int choice = scanner.nextInt();
if(choice == 0) {
ordering = false;
} else if(choice > 0 && choice <= menu.length) {
System.out.print("请输入份数:");
int quantity = scanner.nextInt();
orders[choice-1] += quantity;
total += prices[choice-1] * quantity;
} else {
System.out.println("输入无效!");
}
}
// do-while循环确认支付
boolean paid = false;
do {
System.out.printf(