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
}
}
CodePudding user response:
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.
CodePudding user response:
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.