重复提示直到输入正确

Joh*_*SJA 3 scala scala-2.8

我最近正在接收Scala.我以前习惯了C和Java.我想知道是否有更优雅的方式反复询问输入,直到给出正确的输入.

val choiceType = {
      var in = ""
      var pass = false
      do {
    in = readLine()
    pass = in match {
        case "1" => println("Not implemented"); true
        case "2" => println("Not implemented"); true
        case "3" => println("Not implemented"); true
        case "4" => println("Not implemented"); true
        case "5" => println("Thanks for using."); true
        case _ => println("Error input. Please enter again. (Possible value: 1 - 5)"); false
    }
      } while (!pass)
      in.toInt
    }
    if (choiceType == 5) System.exit(0)
Run Code Online (Sandbox Code Playgroud)

我想知道在Scala中是否有更好的方法可以做到这一点?

Rex*_*err 7

你可以Iterate.continually反复使用其中一个做同样的事情,直到你施加一些停止条件(带dropWhile),或者你可以Iterator.iterate用来给你前一行,以防你想在错误信息中使用它:

val choiceType = Iterator.iterate(readLine())(line => {
  println("Error input: "+line+".  Please enter again (from 1-5).)")
  readLine()
}).collect(line => line match {
  case "1" => println("Not implemented"); line
  case "2" => println("Not implemented"); line
  case "3" => println("Not implemented"); line
  case "4" => println("Not implemented"); line
  case "5" => println("Thanks for using."); line
}).next.toInt
Run Code Online (Sandbox Code Playgroud)

它的工作方式是从readLine开始,然后如果它需要另一行,它会根据前一行宣布一条错误消息(显然是错误的)并读取另一行.然后使用collect块来选择正确的输入; 错误的输入只是没有被收集而落空.在这种情况下,因为你想把它变成一个整数,我只是通过这条线.现在,我们只想要一个好的条目,所以我们得到next一个并将其转换为int.

您还可以使用递归函数来执行类似的操作:

def getChoice: String = {
  val line = readLine()
  line match {
    case "1" => println("Not implemented"); line
    case "2" => println("Not implemented"); line
    case "3" => println("Not implemented"); line
    case "4" => println("Not implemented"); line
    case "5" => println("Thanks for using."); line
    case _ => println("Error, blah blah."); getChoice
  }
}
val choiceType = getChoice.toInt
Run Code Online (Sandbox Code Playgroud)

这里的诀窍是,在输入错误的情况下,您只需再次调用该函数.因为这是函数中发生的最后一件事,Scala将避免真正的函数调用并再次跳转到开头(尾递归),因此您不会溢出堆栈.