Can anyone teach me where to insert try/catch into this code for making sure it won't crash if user enters a string that isn’t “Quit” or also isn’t a number? The following code is used for calculating the average of some numbers. My professor didn't tell us which exception we shall use. Also I am not quite familiar with them.
import io.StdIn._
def sumAndCount() : (Int, Int) = {
println("Please enter a number; or enter Quit:")
val input = readLine.toLowerCase.trim
input match {
case "quit" => (0, 0)
case _ => val (sum, count) = sumAndCount()
(input.toInt+sum, count + 1)
}
}
val (sum, count) = sumAndCount()
val aver = sum.toDouble/count
println(f"The average is $aver")
toInton a string you can getNumberFormatException. I believe you should redesign this code, it doesn't even work.