Menu
Coddy logo textTech

Add Expense

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

challenge icon

Challenge

Medium

In the previous lesson, you created a menu loop that exits when the user selects option 5. Now, implement the "Add Expense" functionality for option 1.

Modify your program to:

  1. Create a MutableList<Double> called expenses before the loop to store expense amounts
  2. When the user selects option 1:
    • Print Enter expense amount:
    • Read the next input, convert it to Double, and add it to the expenses list
    • Print Expense added!
  3. Option 5 should still print Goodbye! and exit
  4. All other options (2, 3, 4, or invalid) should still print Invalid option

Input format:

Menu choices and expense amounts as strings. When option 1 is selected, the next input will be the expense amount.

Output format:

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

Example:

If the inputs are 1, 25.50, 1, 10.00, 3, 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:
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:
Invalid option
--- 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() {
    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 == "5") {
            println("Goodbye!")
            break
        } else {
            println("Invalid option")
        }
    }
}

All lessons in Fundamentals

Practice on your own: Kotlin playground