Jerry Pass
Jerry Pass

Reputation: 105

Reading multiple integers from line in text file

I am using Scala and reading input from the console. I am able to regurgitate the strings that make up each line, but if my input has the following format, how can I access each integer within each line?

2 2
1 2 2
2 1 1

Currently I just regurgitate the input back to the console using

object Main {
  def main(args: Array[String]): Unit = {
    for (ln <- io.Source.stdin.getLines) println(ln)
    //how can I access each individual number within each line?
  }
}

And I need to compile this project like so:

$ scalac main.scala

$ scala Main <input01.txt
2 2
1 2 2
2 1 1

Upvotes: 0

Views: 164

Answers (2)

Yann
Yann

Reputation: 483

The following will give you a flat list of numbers.

val integers = (
  for {
    line <- io.Source.stdin.getLines
    number <- line.split("""\s+""").map(_.toInt)
  } yield number
)

As you can read here, some care must be taken when parsing the numbers.

Upvotes: -1

Levi Ramsey
Levi Ramsey

Reputation: 20561

A reasonable algorithm would be:

  • for each line, split it into words
  • parse each word into an Int

An implementation of that algorithm:

io.Source.stdin.getLines  // for each line...
  .flatMap(
    _.split("""\s+""")    // split it into words
      .map(_.toInt)       // parse each word into an Int
  )

The result of this expression will be an Iterator[Int]; if you want a Seq, you can call toSeq on that Iterator (if there's a reasonable chance there will be more than 7 or so integers, it's probably worth calling toVector instead). It will blow up with a NumberFormatException if there's a word which isn't an integer. You can handle this a few different ways... if you want to ignore words that aren't integers, you can:

import scala.util.Try

io.Source.stdin.getLines
  .flatMap(
    _.split("""\s+""")
      .flatMap(Try(_.toInt).toOption)
  )

Upvotes: 2

Related Questions