我是 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)
关于arrays - scala中的输入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21737197/