hartwall
hartwall

Reputation: 33

(Press any key to continue) in Scala

I'm a scala-novice with a question.

I want to read a text from a file and return three lines at a time and then wait for (any) keyboard input. The problem is to make the program wait for the input before proceeding. For-loops and such obviously ignore readLine():s.

thanks

val text = source.fromFile(file.txt).getLines.toList
var line = 0

while (line <= text.size)
    readLine(text(line) + "\n" + <Press any key to continue>)
    line += 1

Upvotes: 3

Views: 2253

Answers (1)

Justin Pihony
Justin Pihony

Reputation: 67085

You could do something like this:

def getNext3From[T](list : Seq[T]) = {
  val (three, rest) = list splitAt 3 //splits into two lists at the 3 index. Outputs a tuple of type (Seq[T],Seq[T])
  println(three) //calls tostring on the list of three items
  println("Press any key to continue")
  readChar() //waits for any key to be pressed
  rest //returns the remainder of the list
}

@scala.annotation.tailrec //Makes sure that this is a tail recursive method
//Recursive method that keeps requesting the next 3 items and forwarding the new list on until empty
def recursiveLooper[T](list : Seq[T]) : Seq[T] = {
  list match {
    case Nil => List()
    case rlist => recursiveLooper(getNext3From(rlist)) 
  }
}

sample -> recursiveLooper(1 to 9)

Upvotes: 5

Related Questions