查看所有开支
本课属于 Coddy Swift 学习旅程的“基础知识”单元。第 80 课,共 86 课。
挑战
简单在上一课中,你实现了“Add expense”功能。现在,为选项 "2" 实现“View all expenses”功能。
修改代码以处理选项 "2":
- 当用户输入
"2"时,检查expenses数组是否为空 - 如果数组为空,打印
No expenses recorded. - 如果数组中有支出,打印
Your expenses:,然后将每笔支出各占一行打印出来,格式为- $后跟金额,金额格式与 Swift 打印Double的格式相同(例如,25.50会打印为- $25.5) - 选项
"3"和"4"仍应打印Coming soon... - 选项
"1"和"5"应继续像以前一样工作
预期行为:
- 没有支出时输入
"2",打印No expenses recorded. - 有支出时输入
"2",打印标题,并用短横线和美元符号列出每笔支出
交互示例:
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
2
No expenses recorded.
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
2
Your expenses:
- $25.5
- $10.0
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 == "1" {
print("Enter expense amount:")
if let input = readLine(), let amount = Double(input) {
expenses.append(amount)
print("Expense added!")
}
} else if choice == "2" {
print("Coming soon...")
} else if choice == "3" {
print("Coming soon...")
} else if choice == "4" {
print("Coming soon...")
} else if choice == "5" {
print("Goodbye!")
break
} else {
print("Coming soon...")
}
}基础知识中的所有课
自己练习: Swift 在线编辑器