用户输入scala spark的类型检查

k3bvogb1  于 2021-07-13  发布在  Spark
关注(0)|答案(1)|浏览(306)

我正在尝试对用户插入的输入进行类型检查,但我不知道该怎么做。我的代码是:

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
    }

但当我尝试输入“a”这样的字符串时,我会收到以下错误:

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)

有人能解释我做错了什么吗?

pgccezyw

pgccezyw1#

您可以使用 scala.io.StdIn.readLine() 然后尝试将其解析为int,并使用模式匹配来处理有效int和错误的大小写。
像这样:

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

   //...
  }
}

相关问题