How to read from standard input line by line?

后端 未结 6 581
走了就别回头了
走了就别回头了 2020-12-22 17:19

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 cla         


        
6条回答
  •  时光取名叫无心
    2020-12-22 17:33

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

    this is so verbose, you'd rather use java.util.Scanner instead.

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

提交回复
热议问题