Chapter 5 - Section 2
fun main(args: Array<String>) {
try {
val mathLib = MathLib()
while (true) {
val number = MathLib.getInput("Enter a number: ")
mathLib.addValue(number)
println("Current total: ${mathLib.runningTotal}")
}
} catch (e: NumberFormatException) {
println("${e.message} is not a number")
} catch (e: Exception) {
println(e.message)
}
}
class MathLib {
var runningTotal = 0.0
fun addValue(value: Double) {
runningTotal += value
}
companion object {
fun addValues(number1: Double, number2: Double) = number1 + number2
fun getInput(prompt: String): Double {
print(prompt)
val string: String? = readLine()
val number = string!!.toBigDecimal()
return number.toDouble()
}
}
}