source

표준 입력에서 한 줄씩 읽는 방법

bestscript 2022. 11. 24. 23:41

표준 입력에서 한 줄씩 읽는 방법

표준 입력에서 한 줄씩 읽기 위한 스칼라 레시피는 무엇입니까? 동등한 자바 코드:

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. 단, 이는 최종 null 값을 확인해야 하기 때문에 다소 추합니다.

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대신.

좀 더 예쁜 접근법이scala.io.Source:

object ScannerTest {
  def main(args: Array[String]) {
    for (ln <- io.Source.stdin.getLines) println(ln)
  }
}

콘솔의 경우 를 사용할 수 있습니다.Console.readLine. 다음과 같이 쓸 수 있습니다(빈 줄에서 정지하는 경우).

Iterator.continually(Console.readLine).takeWhile(_.nonEmpty).foreach(line => println("read " + line))

파일을 cat하여 입력을 생성하는 경우 null 또는 empty 중 하나를 사용하여 중지해야 할 수 있습니다.

@inline def defined(line: String) = {
  line != null && line.nonEmpty
}
Iterator.continually(Console.readLine).takeWhile(defined(_)).foreach(line => println("read " + line))
val input = Source.fromInputStream(System.in);
val lines = input.getLines.collect

재귀 버전(컴파일러는 힙 사용률 향상을 위해 테일 재귀를 감지함),

def read: Unit = {
  val s = scala.io.StdIn.readLine()
  println(s)
  if (s.isEmpty) () else read 
}

의 사용에 주의해 주세요.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]())
}

사용하지 않을 수 있습니까?

var userinput = readInt // for integers
var userinput = readLine 
...

여기에서 이용 가능 : Scaladoc API

다른 코멘트에서 간단히 설명했듯이는 Scala 2.11.0 이후 폐지되었습니다.다음으로 대체할 수 있습니다.

// Read STDIN lines until a blank one
import scala.io.StdIn.readLine

var line = ""
do {
  line = readLine()
  println("Read: " + line)
} while (line != "")

언급URL : https://stackoverflow.com/questions/4585655/how-to-read-from-standard-input-line-by-line