请考虑以下代码
val sc = new java.util.Scanner (System.in)
while (sc.hasNext()) {
var temp = sc.nextLine()
println(temp.nonEmpty)
println (temp)
}
Run Code Online (Sandbox Code Playgroud)
每当我按enter空行时,程序只是等待下一个输入发生,并且不执行内部语句
例如
input:
<enter>
<enter>
1
Run Code Online (Sandbox Code Playgroud)
原因
output:
<space>
false
<space>
false
1
true
Run Code Online (Sandbox Code Playgroud)
我试图让用户输入行列表,并退出空行
例如.
1 2 3 4
5 6 7 8
<enter> // -> will exit
Run Code Online (Sandbox Code Playgroud)
我怎么做到这一点?
我认为这有点像惯用语:
Iterator.continually(scala.io.StdIn.readLine).takeWhile(_.nonEmpty).foreach(line =>
println(s"read $line")
)
Run Code Online (Sandbox Code Playgroud)