Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over array elements in scala

Tags:

scala

sbt

Heads up, I'm new to Scala

object ch3
{
  def main(args: Array[String]): Unit =
  {
    var foo =  Array (scala.io.StdIn.readLine().split(" ").map(_.toInt))
    foo.foreach(println)
  }
}

Scenario: The input contains 3 space separated integers read from stdin, like 1 2 3. How can I iterate over that array and print the elements?

The problem is that when I try to print the array elements, I get this value [I@7ff9c904.


1 Answers

The output of scala.io.StdIn.readLine().split(" ").map(_.toInt) is already an Array of Int. You're passing it to Array, which creates a new single-element array containing the output of map.

Just remove the outer Array.

var foo = scala.io.StdIn.readLine().split(" ").map(_.toInt)
foo.foreach(println)
like image 103
Willis Blackburn Avatar answered Oct 23 '25 08:10

Willis Blackburn



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!