sytuacnh
sytuacnh

Reputation: 23

Using Try and Catch for Exception in Scala

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")

Upvotes: 1

Views: 678

Answers (1)

Łukasz
Łukasz

Reputation: 8673

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")

You may also want to handle the case when user types only quit, atm result will be NaN.

Please take look at problems with your code. You want to call this function recursive like this, not like you did it.

Upvotes: 1

Related Questions