Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input array in scala

I am new to scala, how to read numbers of integer given in one line? For example:

5
10 20 30 40 50

I want to store it in an array. How to split the input and store it in array?

Single integer can be read by readInt() method and then I read input using readLine(), but don't know how to split and store it in array.

like image 203
user2124441 Avatar asked Jul 20 '26 12:07

user2124441


1 Answers

Without comment:

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)

With comment, I really want 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"
           ^

But it occurs to me that for your use case, you want a simple syntax to scan for ints.

Without having to repeat myself:

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

like image 72
som-snytt Avatar answered Jul 22 '26 02:07

som-snytt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!