0

How do I populate an array with matrix elements from a file in Scala? I know that

    for (val line<- Source.fromFile("mask.txt").getLines){
    }

will fetch the elements row by row but how do I split each row into individual elements and store them as elements of an array?

3 Answers 3

1

You could just call split on line and you'll get back an array of elements to do whatever it is you wish with each element.

for (val line<- Source.fromFile("mask.txt").getLines){
    line.split(<your delimiter>);    
}

The result of the split will be an Array[java.lang.String]

Sign up to request clarification or add additional context in comments.

Comments

0

If mask.txt looks like this:

1,2,3
4,5,6
7,8,9

Then you can do this:

Source.fromFile("mask.txt").getLines.map(_.split(",")).toArray

to get an Array of Arrays that is basically:

Array(Array(1, 2, 3),
      Array(4, 5, 6),
      Array(7, 8, 9))

3 Comments

I get "error: value toArray is not a member of Iterator[Array[java.lang.String]]" on trying this.
@user3039976, are you using an old version of scala?
@user3039976, WOW! That's super-crazy out of date. It was released over 4 years ago! You should update to 2.10.3 immediately.
0

This worked for me.

    var y = new ArrayBuffer[String]()
    for(val line<- Source.fromFile("mask.txt").getLines){
        for( val ele <- line.split(" ")){
            y +=ele
        }
    }

Comments

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.