LoginSignup
49
31

More than 5 years have passed since last update.

Scalaの標準入力

Last updated at Posted at 2016-02-03

PaizaAOJなどのオンラインプログラミングを久しぶりにやると、忘れてることが多いのでメモ。
標準出力を扱う方法がいくつかあるので、状況によって使い分けます。

単一行を読み込む場合

単純に一行読み込みたい場合はio.StdIn.readLine()を使用します。

例:スペース区切の文字を昇順ソートして出力

input
 e c a b d 
Main.scala
object Main extends App {
  val strAry = io.StdIn.readLine().split(' ')
  println(strAry.sorted.mkString(" "))
}
// 出力結果
// a b c d e

複数行読み込む場合

複数行読み込みたい場合はio.Source.stdin.getLines()を使用し、for式で処理します。

例:各行の数字を昇順ソートして出力
input
 1 4 3 5 2
 3 5 2 1 4
 1 3 2 4 5
Main.scala
object Main extends App {
  for(line <- io.Source.stdin.getLines()) {
    val numAry = line.split(' ').map { _.toInt }
    println(numAry.sorted.mkString(" "))
  }
}
// 出力結果
// 1 2 3 4 5
// 1 2 3 4 5
// 1 2 3 4 5

参考:java.util.Scannerを利用する

ScalaではJavaクラスを簡単に利用することができます。

input
 1a2a3a
Main.scala
object Main extends App {
  val scanner = new java.util.Scanner(System.in)
  scanner.useDelimiter("a")
  while(scanner.hasNext){
    println(scanner.next)
  }
}
// 出力結果
// 1
// 2
// 3
参考
49
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
49
31