Menu
CoddyTech

ניקוי הכול

חלק מהיחידה יסודות במסלול ה-Swift של Coddy. שיעור 82 מתוך 86.

challenge icon

אתגר

קל

בשיעור הקודם מימשת את התכונה "Show total and average". עכשיו יש לממש את התכונה "Clear all expenses" עבור האפשרות "4".

יש לשנות את הקוד כך שיטפל באפשרות "4":

  1. כאשר המשתמש מזין "4", יש להסיר את כל האיברים ממערך expenses
  2. יש להדפיס את All expenses cleared! לאחר ניקוי המערך
  3. כל שאר האפשרויות ("1", "2", "3" ו-"5") צריכות להמשיך לפעול כרגיל

רמז: יש להשתמש בשיטה removeAll() כדי להסיר את כל האיברים מהמערך.

התנהגות צפויה:

  • כאשר מזינים "4", יש לנקות את מערך ההוצאות ולאשר זאת בהודעה
  • לאחר הניקוי, הצגת ההוצאות צריכה להציג את No expenses recorded.
  • לאחר הניקוי, הצגת הסכום הכולל והממוצע צריכה להציג את No expenses to calculate.

אינטראקציה לדוגמה:

1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
15.0
Expense 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:
- $15.0
- $25.0
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
4
All expenses cleared!
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
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" {
        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" {
        print("Coming soon...")
    } else if choice == "5" {
        print("Goodbye!")
        break
    } else {
        print("Coming soon...")
    }
}

כל השיעורים ביחידה יסודות

תרגלו בעצמכם: Swift אונליין