如何逐行读取标准输入? [英] How to read from standard input line by line?
本文介绍了如何逐行读取标准输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从标准输入逐行阅读的Scala配方是什么?类似于等效的java代码:
What's the Scala recipe for reading line by line from the standard input ? Something like the equivalent java code :
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());
}
}
}
推荐答案
最直接的方法只使用 readLine()
,它是 Predef
的一部分。然而,这需要检查最终的空值是否相当丑陋:
The most straight-forward looking approach will just use readLine()
which is part of Predef
. however that is rather ugly as you need to check for eventual null value:
object ScannerTest {
def main(args: Array[String]) {
var ok = true
while (ok) {
val ln = readLine()
ok = ln != null
if (ok) println(ln)
}
}
}
这是如此冗长,你宁愿使用 java.util.Scanner
。
this is so verbose, you'd rather use java.util.Scanner
instead.
我认为更漂亮方法将使用 scala.io.Source
:
I think a more pretty approach will use scala.io.Source
:
object ScannerTest {
def main(args: Array[String]) {
for (ln <- io.Source.stdin.getLines) println(ln)
}
}
这篇关于如何逐行读取标准输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文