添加开支
本课属于 Coddy Swift 学习旅程的“基础知识”单元。第 79 课,共 86 课。
挑战
简单在上一课中,你创建了一个菜单循环,用户输入 "5" 时循环会退出。现在,为选项 "1" 实现“添加支出”功能。
修改代码以处理选项 "1":
- 用户输入
"1"时,打印Enter expense amount: - 使用
readLine()读取支出金额 - 将输入转换为
Double,并将其追加到expenses数组中 - 成功添加支出后,打印
Expense added! - 选项
"2"、"3"和"4"仍应打印Coming soon... - 选项
"5"仍应打印Goodbye!并退出
预期行为:
- 输入
"1"时,提示输入支出金额,将金额添加到数组中,并显示确认信息 - 每次操作后,菜单都会继续显示,直到输入
"5"
交互示例:
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
25.50
Expense added!
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
10.00
Expense added!
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
var expenses: [Double] = []
while true {
// 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")
let choice = readLine()
if choice == "5" {
print("Goodbye!")
break
} else {
print("Coming soon...")
}
}基础知识中的所有课
自己练习: Swift 在线编辑器