2014-02-12 50 views
2

我是新來的斯卡拉,如何讀取一行中給出的整數數字?例如:在斯卡拉輸入數組

5 
10 20 30 40 50 

我想將它存儲在一個數組中。如何分割輸入並將其存儲在數組中?

可以通過readInt()方法讀取單個整數,然後使用readLine()讀取輸入,但不知道如何拆分並將其存儲在數組中。

回答

1

試試這個:

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

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

+0

不需要'.toArray'; 'split'返回一個'Array' – dhg

+0

問題解決! –

+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

您總是可以爲fscanf貢獻代碼... :)畢竟,f內插函數_is_是一個宏。 –