Average

Report a typo

We have a program that takes a string of comma-separated integers as input and attempts to convert it into a list of integers.

  • If any of the values in the input string are not valid integers, the program should catch the exception and print the following message: Invalid input!
  • If the list is empty, the program should throw IllegalArgumentException, and then, when catching it, it should print the following message: Cannot calculate average of an empty list!
  • If all values are valid integers, the program should calculate the average of the list.
  • If an unexpected error is caught, the program should print: An error occurred!

Complete the catch block to handle all exceptions as intended.

Sample Input 1:

10,20,30

Sample Output 1:

20.0
Write a program in Kotlin
fun main() {
val input = readln()
try {

val list = input.split(",")
if (list == listOf("")) {
throw IllegalArgumentException()
}
val numbers = list.map { it.toInt() }
val average = numbers.average()
println(average)

} catch (...) { // Write the code to handle each exception as recommended
...
}
}

Create a free account to access the full topic