scala - Repeated prompt until correct input -


I have been using Scala recently, I have been used before C and Java, I am thinking that the right input There is another great way to repeatedly demand input.

  val choiceType = {var in = "var pass = false do {in = readLine () pass = in match {case" 1 "=> Println ("not implemented"); True case "2" => Println ("not implemented"); The truth is the case "3" => Println ("not implemented"); The truth is the case "4" => Println ("not implemented"); The truth is "5" => Println ("Thanks for using."); True case _ = & gt; Println ("Error input. Please re-enter. (Potential value: 1 - 5)"); False}} while (! Pass) in.toInt} if (choiceType ==5) System.exit (0)   

I am thinking that there is a better way to do this in Scala ? You can either use Iterate.continually and again Unless you apply a position with some stopping status ( dropWhile ), or you can use it to return the previous line to Iterator.iterate if you want to The error message you want to use in your:

  val option type = Iterator.iterate (readLine ()) (line => {println ("Error input:" + line + ". Please enter 1-5.) ") Line (" not applicable "); Line case "2" = & gt; Println ("not implemented"); Lin (& gt; line match {case "1" => gt; println; line case "3" => println ("not implemented"); line case "4" => println ("apply Not done "); line case" 5 "=> println (" Thank you for using. "); Line}). Next.toInt   

The way it works it is starting wi a readline, and then if it requires a second line, then an error message based on the previous line (Obviously one was wrong) and read another row, then you use the collect block to select your correct input; Incorrect input only falls without collecting. In this case, since you want to convert it to an integer, I am just going through the line. Now, we only want a good entry, so we get the next and converts it into an integer.

You can also use a recursive function to perform the same function:

  def getChoice: string = {val line = readLine () line match {case " 1 "= & gt; Println ("not implemented"); Line case "2" = & gt; Println ("not implemented"); Line case "3" = & gt; Println ("not implemented"); Line case "4" = & gt; Println ("not implemented"); Line case "5" = & gt; Println ("Thanks for using."); Line case _ = & gt; Println ("error, blah blah."); GetChoice}} val choiceType = getChoice.toInt   

Here's the trick that you get the wrong input, you call the function again. Since the last thing in the function is that, Scala wants to avoid a real function call and just starts again (tail-recursion), so you will not overflow the stack.

Comments