Menu
Coddy logo textTech

View All Expenses

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 87 of 93.

challenge icon

Challenge

Medium

In the previous lesson, you implemented the "Add Expense" functionality. Now, implement the "View All Expenses" functionality for option 2.

Modify your program to handle option 2:

  • If the expenses list is empty, print No expenses recorded.
  • If there are expenses, print Your expenses: followed by each expense on a new line, formatted as - $amount (where amount is the expense value)

All other options should continue working as before:

  • Option 1: Add expense
  • Option 5: Print Goodbye! and exit
  • Options 3, 4, or invalid: Print Invalid option

Input format:

Menu choices and expense amounts as strings.

Output format:

The menu, followed by the appropriate response for each action.

Example:

If the inputs are 2, 1, 15.50, 1, 8.25, 2, and 5, the output should be:

--- Expense Tracker ---
1. Add Expense
2. View All Expenses
3. Total and Average
4. Clear All
5. Exit
Choose an option:
No expenses recorded.
--- Expense Tracker ---
1. Add Expense
2. View All Expenses
3. Total and Average
4. Clear All
5. Exit
Choose an option:
Enter expense amount:
Expense added!
--- Expense Tracker ---
1. Add Expense
2. View All Expenses
3. Total and Average
4. Clear All
5. Exit
Choose an option:
Enter expense amount:
Expense added!
--- Expense Tracker ---
1. Add Expense
2. View All Expenses
3. Total and Average
4. Clear All
5. Exit
Choose an option:
Your expenses:
- $15.5
- $8.25
--- Expense Tracker ---
1. Add Expense
2. View All Expenses
3. Total and Average
4. Clear All
5. Exit
Choose an option:
Goodbye!

Try it yourself

fun main() {
    val expenses = mutableListOf<Double>()
    
    while (true) {
        println("--- Expense Tracker ---")
        println("1. Add Expense")
        println("2. View All Expenses")
        println("3. Total and Average")
        println("4. Clear All")
        println("5. Exit")
        println("Choose an option:")
        
        val choice = readLine()
        
        if (choice == "1") {
            println("Enter expense amount:")
            val amount = readLine()!!.toDouble()
            expenses.add(amount)
            println("Expense added!")
        } else if (choice == "5") {
            println("Goodbye!")
            break
        } else {
            println("Invalid option")
        }
    }
}

All lessons in Fundamentals

Practice on your own: Kotlin playground