1

I have 10 lines of input I am reading from stdin via readLine(). How can I read these 10 lines into an array of strings?

2 Answers 2

3

A slightly more direct approach:

Array.fill(10){readLine()}
Sign up to request clarification or add additional context in comments.

Comments

1

You can create a range from 1 to 10 with 1 to 10 and then map over it while not caring about the actual numbers, only reading lines:

(1 to 10).map(_ => readLine()).toArray

As asked in your comment, printing out arrays easily can't be done just by calling println on them, but Seqs support it:

scala> println(Array("a", "b", "c"))
[Ljava.lang.String;@60b85ba1

scala> println(Seq("a", "b", "c"))
List(a, b, c)

3 Comments

I had tried this already actually and when I printed it, it gave me a bunch of gibberish for some reason: [Ljava.lang.String@bunch of numbers
Because Array is just a Java array meaning the toString method is a default method and prints the type + hashCode. Use .toSeq instead to get a Scala sequence. Updated my answer with examples.
To print out an array, try: a.mkString(", ")

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.