Menu
CoddyTech

Thêm 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 79 trên 86.

challenge icon

Thử thách

Dễ

Trong bài học trước, bạn đã tạo một vòng lặp menu thoát khi người dùng nhập "5". Bây giờ, hãy triển khai tính năng "Add expense" cho tùy chọn "1".

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

  1. Khi người dùng nhập "1", in ra Enter expense amount:
  2. Đọc số tiền chi tiêu bằng readLine()
  3. Chuyển đầu vào thành Double và thêm vào mảng expenses
  4. In ra Expense added! sau khi thêm khoản chi thành công
  5. Các tùy chọn "2", "3" và "4" vẫn phải in ra Coming soon...
  6. Tùy chọn "5" vẫn phải in ra Goodbye! rồi thoát

Hành vi mong đợi:

  • Khi nhập "1", hãy yêu cầu nhập số tiền chi tiêu, thêm số tiền đó vào mảng và xác nhận
  • Menu tiếp tục hiển thị sau mỗi thao tác cho đến khi nhập "5"

Ví dụ tương tác:

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!

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 == "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