任何人都可以教我在这段代码中插入 try / catch ,以确保在用户输入的字符串不是“退出”时不会崩溃或者也不是数字?以下代码用于计算某些数字的平均值。我的教授没有告诉我们我们将使用哪个例外。我也不太熟悉它们。
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")
答案 0 :(得分:1)
import io.StdIn._
def sumAndCount(sum: Int, count: Int) : (Int, Int) = {
println("Please enter a number; or enter Quit:")
val input = readLine.toLowerCase.trim
input match {
case "quit" => (sum, count)
case _ => try {
val number = input.toInt
sumAndCount(sum + number, count + 1)
} catch {
case _: NumberFormatException =>
println("that's not a number, try again")
sumAndCount(sum, count)
}
}
}
val (sum, count) = sumAndCount(0, 0)
val aver = sum.toDouble / count
println(f"The average is $aver")
您可能还想处理仅在用户类型退出时的情况,atm结果将为NaN
。
请查看代码问题。你想像这样递归调用这个函数,而不是像你那样。