Menu
CoddyTech

退出程序

本课属于 Coddy Swift 学习旅程的“基础知识”单元。第 78 课,共 86 课。

challenge icon

挑战

简单

在上一课中,你打印了支出跟踪器的菜单。现在,添加一个循环,让菜单持续显示并读取用户输入,直到用户选择退出。

修改代码以完成以下操作:

  1. 创建一个类型为 [Double] 的空数组 expenses,用于存储支出
  2. 使用 while true 循环让程序持续运行
  3. 在循环中,像之前一样打印菜单
  4. 使用 readLine() 读取用户的选择
  5. 如果用户输入 "5",打印 Goodbye!,并使用 break 退出循环
  6. 对于其他任何输入,打印 Coming soon...(我们会在后续课程中实现其他选项)

预期行为:

  • 菜单会反复显示,直到用户输入 "5"
  • 输入 "5" 时,打印 Goodbye! 并退出循环
  • 对于选项 "1"、"2"、"3" 或 "4"(或任何其他输入),打印 Coming soon... 并再次显示菜单

交互示例:

1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Coming soon...
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
5
Goodbye!

亲手试试

// Daily Expense Tracker - Menu Display

// TODO: Write your code below to print the menu options
// Each option should be on its own line with the format: "number. option text"
print("1. Add expense")
print("2. View all expenses")
print("3. Show total and average")
print("4. Clear all expenses")
print("5. Exit")

基础知识中的所有课

自己练习: Swift 在线编辑器