Menu
Coddy logo textTech

Handling Errors

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

challenge icon

Challenge

Medium

In the previous lesson, you implemented the "Clear All" functionality. Now, add input validation to handle cases where the user enters an invalid expense amount.

Modify your program to handle errors when adding expenses (option 1):

  • When the user enters an expense amount, use toDoubleOrNull() to safely convert the input
  • If the conversion returns null (invalid input), print Invalid amount! instead of adding the expense
  • If the conversion succeeds, add the expense and print Expense added! as before

All other options should continue working as before:

  • Option 1: Add expense (with validation)
  • Option 2: View all expenses
  • Option 3: Total and average
  • Option 4: Clear all expenses
  • Option 5: Print Goodbye! and exit
  • Invalid options: 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 1, abc, 1, 25.0, 1, hello, 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:
Enter expense amount:
Invalid amount!
--- 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:
Invalid amount!
--- Expense Tracker ---
1. Add Expense
2. View All Expenses
3. Total and Average
4. Clear All
5. Exit
Choose an option:
Your expenses:
- $25.0
--- Expense Tracker ---
1. Add Expense
2. View All Expenses
3. Total and Average
4. Clear All
5. Exit
Choose an option:
Goodbye!

Hint: The toDoubleOrNull() method returns null if the string cannot be converted to a Double, instead of crashing. Use the Elvis operator or a null check to handle this case.

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 == "2") {
            if (expenses.isEmpty()) {
                println("No expenses recorded.")
            } else {
                println("Your expenses:")
                for (expense in expenses) {
                    println("- \$$expense")
                }
            }
        } else if (choice == "3") {
            if (expenses.isEmpty()) {
                println("No expenses recorded.")
            } else {
                val total = expenses.sum()
                val average = total / expenses.size
                println("Total: \$$total")
                println("Average: \$$average")
            }
        } else if (choice == "4") {
            expenses.clear()
            println("All expenses cleared!")
        } else if (choice == "5") {
            println("Goodbye!")
            break
        } else {
            println("Invalid option")
        }
    }
}

All lessons in Fundamentals

Practice on your own: Kotlin playground