(在Scala中按任意键继续)

时间:2014-11-25 18:11:50

标签: scala loops input return readline

我是一个有问题的scala-novice。

我想从文件中读取文本并一次返回三行,然后等待(任何)键盘输入。问题是让程序在继续之前等待输入。 For循环等明显忽略readLine():s。

感谢

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

1 个答案:

答案 0 :(得分:2)

你可以这样做:

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

样本 - &gt; recursiveLooper(1 to 9)