(按任意键继续)在 Scala 中

har*_*all 3 loops scala return input readline

我是一个 scala 新手,有个问题。

我想从文件中读取文本并一次返回三行,然后等待(任何)键盘输入。问题是让程序在继续之前等待输入。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
Run Code Online (Sandbox Code Playgroud)

Jus*_*ony 5

你可以这样做:

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)) 
  }
}
Run Code Online (Sandbox Code Playgroud)

样品->recursiveLooper(1 to 9)