すべての支出を表示
CoddyのSwiftジャーニー「基礎」セクションの一部 — レッスン 80/86。
チャレンジ
簡単前のレッスンでは、「Add expense」機能を実装しました。今回は、オプション "2" の「View all expenses」機能を実装しましょう。
オプション "2" を処理するようにコードを修正してください:
- ユーザーが
"2"を入力したとき、expenses配列が空かどうかを確認します - 配列が空の場合は、
No expenses recorded.と出力します - 配列に支出が記録されている場合は、
Your expenses:と出力し、その後に各支出を- $X.XX(X.XX は支出額)の形式でそれぞれの行に出力します - オプション
"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...")
}
}