在scala中输入数组

时间:2014-02-12 19:01:18

标签: arrays scala input

我是scala的新手,如何读取一行中给出的整数?例如:

5
10 20 30 40 50

我想将它存储在一个数组中。如何拆分输入并将其存储在数组中?

单个整数可以通过readInt()方法读取,然后我使用readLine()读取输入,但不知道如何拆分并将其存储在数组中。

2 个答案:

答案 0 :(得分:4)

没有评论:

scala> val in = "10 20 30 40 50"
in: String = 10 20 30 40 50

scala> (in split " ")
res0: Array[String] = Array(10, 20, 30, 40, 50)

scala> (in split " ") map (_.toInt)
res1: Array[Int] = Array(10, 20, 30, 40, 50)

通过评论,我真的想要fscanf

scala> val f"$i%d" = "10"
<console>:7: error: macro method f is not a case class, nor does it have an unapply/unapplySeq member
       val f"$i%d" = "10"
           ^

但是对我来说,对于你的用例,你需要一个简单的语法来扫描整数。

无需重复自己:

scala> val r = """(\d+)""".r
r: scala.util.matching.Regex = (\d+)

scala> r findAllMatchIn in
res2: Iterator[scala.util.matching.Regex.Match] = non-empty iterator

scala> .toList
res3: List[scala.util.matching.Regex.Match] = List(10, 20, 30, 40, 50)

https://issues.scala-lang.org/browse/SI-8268

答案 1 :(得分:1)

试试这个:

val s = readLine
val a: Array[Int] = s.split(" ").map(_.toInt)

或    val a = readLine.split(" ").map(_.toInt);)