Menu
CoddyTech

Xử lý lỗi

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 83 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 "Clear all expenses". Bây giờ, hãy thêm xử lý lỗi cho các đầu vào không hợp lệ trong toàn bộ trình theo dõi chi tiêu.

Sửa code để xử lý các đầu vào không hợp lệ một cách phù hợp:

  1. Khi người dùng nhập lựa chọn menu không hợp lệ (bất kỳ giá trị nào khác "1", "2", "3", "4" hoặc "5"), hãy in ra Invalid option. Please try again.
  2. Khi thêm một khoản chi (lựa chọn "1"), nếu đầu vào không thể chuyển đổi thành một giá trị Double hợp lệ, hãy in ra Invalid amount. Expense not added. rồi quay lại menu mà không thêm gì vào mảng
  3. Tất cả chức năng khác vẫn tiếp tục hoạt động như trước

Hành vi mong đợi:

  • Lựa chọn menu không hợp lệ hiển thị thông báo lỗi rồi hiện lại menu
  • Số tiền chi không hợp lệ hiển thị thông báo lỗi rồi quay lại menu
  • Đầu vào hợp lệ tiếp tục hoạt động như đã triển khai trong các bài học trước

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

1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
7
Invalid option. Please try again.
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
abc
Invalid amount. Expense not added.
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
25.0
Expense added!
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
2
Your expenses:
- $25.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" {
        if expenses.isEmpty {
            print("No expenses recorded.")
        } else {
            print("Your expenses:")
            for expense in expenses {
                print("- $\(expense)")
            }
        }
    } else if choice == "3" {
        if expenses.isEmpty {
            print("No expenses to calculate.")
        } else {
            let total = expenses.reduce(0, +)
            let average = total / Double(expenses.count)
            print("Total: $\(total)")
            print("Average: $\(average)")
        }
    } else if choice == "4" {
        expenses.removeAll()
        print("All expenses cleared!")
    } 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