Menu
CoddyTech

Xem tất cả khoản chi

Thuộc phần Kiến thức nền tảng trong hành trình Swift của Coddy. Bài học 80 trên 86.

challenge icon

Thử thách

Dễ

Trong bài học trước, bạn đã triển khai tính năng "Add expense". Bây giờ, hãy triển khai tính năng "View all expenses" cho tùy chọn "2".

Sửa code để xử lý tùy chọn "2":

  1. Khi người dùng nhập "2", hãy kiểm tra xem mảng expenses có rỗng không
  2. Nếu mảng rỗng, hãy in ra No expenses recorded.
  3. Nếu mảng có các khoản chi, hãy in ra Your expenses:, sau đó in từng khoản chi trên một dòng riêng, theo định dạng - $ theo sau là số tiền như cách Swift in một giá trị Double (ví dụ, 25.50 được in thành - $25.5)
  4. Các tùy chọn "3" và "4" vẫn phải in ra Coming soon...
  5. Các tùy chọn "1" và "5" vẫn phải hoạt động như trước

Hành vi mong đợi:

  • Khi nhập "2" mà không có khoản chi nào, hãy in ra No expenses recorded.
  • Khi nhập "2" và có khoản chi, hãy in tiêu đề và liệt kê từng khoản chi với dấu gạch ngang và ký hiệu đô la

Tương tác mẫu:

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!

Tự làm thử

// 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...")
    }
}

Tất cả bài học trong Kiến thức nền tảng

Tự luyện tập: Playground Swift