1

I am a scala beginner and I face a problem when I am doing my homework because there is null in the text file for example (AFG,Asia,Afghanistan,2020-02-24,1.0,1.0,,,,,0.026,0.026). So, I need to replace the null in array with zero. I read the scala array members and try the update and filter method but I cannot solve it. Can someone help me?

    val filename = "relevant.txt" //Access File
val rf = Source.fromFile(filename).getLines.toArray //Read File as Array


for(line <- rf){ //for loop
  line.(**How to replace the null with 0?**)

  //println(line.split(",")(0))
  if (line.split(",")(0).trim().equalsIgnoreCase(iso_code)){ //check for correct ISO CODE , ignores the casing of the input
    
  total_deaths += line.split(",")(4).trim().toDouble //increases based on the respective array position
 
  sum_of_new_deaths += line.split(",")(5).trim().toDouble
 
  record_count += 1 //increment for each entry

  }
}
3
  • Do you mean you want AFG,Asia,Afghanistan,2020-02-24,1.0,1.0,,,,,0.026,0.026 become AFG,Asia,Afghanistan,2020-02-24,1.0,1.0,0,0,0,0,0.026,0.026 ? Commented Nov 12, 2021 at 14:15
  • yes, that's what I mean Commented Nov 13, 2021 at 0:51
  • val cleanLine = ",\\s*(?=,)".r.replaceAllIn(line,",0") Commented Nov 13, 2021 at 5:56

3 Answers 3

1
val cells = line.split(",")
                .map(_.trim)
                .map(it => if (it.isEmpty) "0" else it)

Then you can use it like total_deaths += cells(4).toDouble


BTW, null usually refers to "null pointer" in scala.

In your case, you don't have any "null pointer", you just have "empty string"

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

Comments

0

What you may do is something like this:

for (line <- rf) {
  val data = line.split(',').toList.map(str => Option(str).filter(_.nonEmpty))
}

That way data would be a List[Option[String]] where empty values will be None, then you may use pattern matching to extra the data you want.

Comments

0

if you had to apply the change where you want:

//line.(**How to replace the null with 0?**)

you could do:

val line2 = if (line.trim().isEmpty) "," else line

then use line2 everywhere else.

As a side thing, if you want to do something more scala, replace .toArray with .toList and have a look at how map, filter, sum etc work.

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.