0

I want to send (integer) values from a csv file to a (Chisel) class here.

I just can't read the values from a csv file - I have already tried all code snippets scattered around the internet. (csv file is in the format below ->)

1321437196.0,
-2132416838.0,
1345437196.0

Code I am using:

val bufferedSource = io.Source.fromFile("sourceFile.csv")
val rows = Array.ofDim[Int](3)
var count = 0
  for (line <- bufferedSource.getLines) {

    rows(count) = line.split(",").map(_.trim).toString.toInt

    count += 1
  }
  bufferedSource.close
println(rows.mkString(" "))

Output:

[Ljava.lang.String;@51f9ef45
[Ljava.lang.String;@2f42c90a
[Ljava.lang.String;@6d9bd75d

I have understood the error message and tried all various snippets mentioned here(Printing array in Scala , Scala - printing arrays) , but I just can't see where I am going wrong here. Just to point out, I don't want a Double value here but want a converted Signed Integer , hence that is why toInt.

Thanks will appreciate help with this!

shodan
  • 177
  • 2
  • 11
  • 2
    split yields an array, you want `split(comma)(0)`. You might consider something simple like `"314.0,".stripSuffix(".0,").toInt`. – som-snytt Mar 02 '20 at 01:27

3 Answers3

3

"1.0".toInt won't work. Need to go from String to Float to Int.

val bufferedSource = io.Source.fromFile("sourceFile.csv")
val rows = bufferedSource.getLines
                         .map(_.split(",").head.trim.toFloat.toInt)
                         .toArray
bufferedSource.close
rows  //res1: Array[Int] = Array(1321437184, -2132416896, 1345437184)
jwvh
  • 50,871
  • 7
  • 38
  • 64
1

Change

line.split(",").map(_.trim).toString.toInt

to

line.split(",")(0).trim.toInt
Suhas NM
  • 960
  • 7
  • 10
0
val bufferedSource = io.Source.fromFile("sourceFile.csv")
val rows = bufferedSource.getLines
                     .map(_.split(",").headOption.mkString.toInt)
bufferedSource.close
Dhirendra
  • 289
  • 3
  • 8