How to read in numbers from n lines into a Scala list?

1k views Asked by At

This is for an online judge. I am trying to learn some Scala in the process.

The input format looks like

4
543534
6756
4564
363773

So the first line is n, and then the next n lines contain elements that need to go into a list.

Right now I read n by using readInt() but I don't know how to then say "now read the next n lines and place everything into a list".

2

There are 2 answers

0
integer-j On BEST ANSWER

Try this:

val n = io.StdIn.readInt
val list = ( 0 to n ).map( (x) -> io.StdIn.readLine ).toList
//...
0
Ben Che On

You can do this in one line if you trust the input and ignore that first range value.

val list = io.StdIn.getLines.drop(1).map(_.toInt).toList