3

I'm trying to do a type checking on an input that the user insert, but I don't know ho to do. My code is:

for(iteration<- 0 to 19) {
      print(movieRecommended(iteration))
      var personalRate = scala.io.StdIn.readDouble()
      if(Try(personalRate.toInt).isSuccess){
        while((personalRate > 5 || personalRate < 1) || personalRate % 0.5 != 0) {
          println("Error: respect the parameters")
          print(movieRecommended(iteration))
          personalRate = scala.io.StdIn.readDouble()
        }
      }
      else println("Error")
    ratingArr(iteration) = personalRate
    }

But when I try to give a string input like "a" I receive this error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "a"
    at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
    at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.base/java.lang.Double.parseDouble(Double.java:549)
    at scala.collection.immutable.StringLike.toDouble(StringLike.scala:321)
    at scala.collection.immutable.StringLike.toDouble$(StringLike.scala:321)
    at scala.collection.immutable.StringOps.toDouble(StringOps.scala:33)
    at scala.io.StdIn.readDouble(StdIn.scala:167)
    at scala.io.StdIn.readDouble$(StdIn.scala:162)
    at scala.io.StdIn$.readDouble(StdIn.scala:241)
    at CollaborativeFilteringUserBasedALS$.$anonfun$askUserInput$1(CollaborativeFilteringUserBasedALS.scala:192)
    at scala.collection.immutable.Range.foreach$mVc$sp(Range.scala:158)
    at CollaborativeFilteringUserBasedALS$.askUserInput(CollaborativeFilteringUserBasedALS.scala:189)
    at CollaborativeFilteringUserBasedALS$.topRated(CollaborativeFilteringUserBasedALS.scala:133)
    at CollaborativeFilteringUserBasedALS$.main(CollaborativeFilteringUserBasedALS.scala:284)
    at CollaborativeFilteringUserBasedALS.main(CollaborativeFilteringUserBasedALS.scala)

Someone can explain me what I'm doing wrong?

Uderr
  • 57
  • 6
  • add a new `val` to cast personalRate to Int first, e.g. `val personalRateInt = tryToInt(personalRate)` where `tryToInt` is from [here](https://stackoverflow.com/a/23811475), and replace the variables in the while statement with this new val. – mck Feb 21 '21 at 10:39

1 Answers1

2

You can read the input as a string using scala.io.StdIn.readLine() then try to parse it to Int and use pattern matching to handle case for valid int and for error.

Something like this :

for (iteration <- 0 to 19) {
  var personalRate = scala.io.StdIn.readLine()

  Try(personalRate.toInt).toOption match {
    case Some(rate) => {
      println(rate)
      // your logic for int 
    }
    case _ => println("Error")
    
   //...
  }
}
blackbishop
  • 30,945
  • 11
  • 55
  • 76