And*_*anu 90 java io scala java.util.scanner
什么是标准输入逐行读取的Scala配方?类似于等效的java代码:
import java.util.Scanner;
public class ScannerTest {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
System.out.println(sc.nextLine());
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 130
最直接的方法只会使用readLine()它的一部分Predef.但是,当你需要检查最终的空值时,这是相当丑陋的:
object ScannerTest {
def main(args: Array[String]) {
var ok = true
while (ok) {
val ln = readLine()
ok = ln != null
if (ok) println(ln)
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是如此冗长,你宁愿使用java.util.Scanner.
我认为一个更漂亮的方法将使用scala.io.Source:
object ScannerTest {
def main(args: Array[String]) {
for (ln <- io.Source.stdin.getLines) println(ln)
}
}
Run Code Online (Sandbox Code Playgroud)
Lan*_*dei 52
对于您可以使用的控制台Console.readLine.你可以写(如果你想停在一个空行):
Iterator.continually(Console.readLine).takeWhile(_.nonEmpty).foreach(line => println("read " + line))
Run Code Online (Sandbox Code Playgroud)
如果您捕获文件以生成输入,则可能需要使用以下命令停止null或empty:
@inline def defined(line: String) = {
line != null && line.nonEmpty
}
Iterator.continually(Console.readLine).takeWhile(defined(_)).foreach(line => println("read " + line))
Run Code Online (Sandbox Code Playgroud)
Jas*_*son 27
val input = Source.fromInputStream(System.in);
val lines = input.getLines.collect
Run Code Online (Sandbox Code Playgroud)
小智 10
你能用吗?
var userinput = readInt // for integers
var userinput = readLine
...
Run Code Online (Sandbox Code Playgroud)
elm*_*elm 10
递归版本(编译器检测尾递归以改进堆使用),
def read: Unit = {
val s = scala.io.StdIn.readLine()
println(s)
if (s.isEmpty) () else read
}
Run Code Online (Sandbox Code Playgroud)
请注意io.StdInScala 2.11 的使用.另请注意,通过这种方法,我们可以在最终返回的集合中累积用户输入 - 除了打印输出外.也就是说,
import annotation.tailrec
def read: Seq[String]= {
@tailrec
def reread(xs: Seq[String]): Seq[String] = {
val s = StdIn.readLine()
println(s)
if (s.isEmpty()) xs else reread(s +: xs)
}
reread(Seq[String]())
}
Run Code Online (Sandbox Code Playgroud)