I am picking up Scala recently. I have been used to C and Java before. I am wondering if there is a more elegant way of asking for input repeatedly until correct input is given.
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)
I am wondering if there is a better way of doing this in Scala?
You could use either Iterate.continually to do the same thing over and over again until you impose some stopping condition (with dropWhile), or you could use Iterator.iterate to give you the previous line in case you want to use it in your error message:
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
The way this works is by starting with a readLine, and then if it needs another line it announces an error message based on the previous line (obviously that one was wrong) and reads another line. You then use a collect block to pick out your correct input; the wrong input just falls through without being collected. In this case, since you want to turn it into an integer, I'm just passing the line through. Now, we only want one good entry, so we get the next one and convert it to an int.
You could also use a recursive function to do a similar thing:
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
Here the trick is that in the case where you get wrong input, you just call the function again. Since that's the last thing that happens in the function, Scala will avoid a true function call and just jump to the beginning again (tail-recursion), so you won't overflow the stack.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With