arrays - scala中的输入数组

标签 arrays scala input

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

5
10 20 30 40 50

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

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

最佳答案

没有评论:

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

关于arrays - scala中的输入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21737197/

相关文章:

python - 从 np.zeros 中选取具有最高值的行

python - 为什么 Python 看不到文件中的所有行?

eclipse - Akka Actors 库是否与 Scala 2.10 的 Scala IDE 一起安装?

html - TurboTable primeng 输入 EnterKey

java - 在 Java 中读取输入 - 帮助

c - 如何在不使用循环的情况下在 C 中初始化 N 维数组

c# - 列表、排序列表和数组列表之间有什么区别? (C#)

c - 为什么c语言编码会出现运行时错误?

scala - 如何为 Scala 3 枚举创建通用方法

scala - 有没有办法避免在这个 scala 代码片段中使用 var