3

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.

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

You could always contribute the code for the fscanf... :) After all, the f interpolator is a macro.
2

Try this:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.