1

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") 
2
  • Hint: with your current code, what happens when something that is neither "Quit" nor a number is entered? (Have you tried it?) Commented Oct 3, 2015 at 18:18
  • when you call toInt on a string you can get NumberFormatException. I believe you should redesign this code, it doesn't even work. Commented Oct 3, 2015 at 18:25

1 Answer 1

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

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.