我是 Scala 初學者,在做作業時遇到問題,因為例如文本檔案中有空值 (AFG,Asia,Afghanistan,2020-02-24,1.0,1.0,,,,,0.026,0.026 )。所以,我需要用 zero 替換陣列中的 null。我閱讀了 Scala 陣列成員并嘗試了更新和過濾方法,但我無法解決它。有人能幫我嗎?
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
}
}
uj5u.com熱心網友回復:
val cells = line.split(",")
.map(_.trim)
.map(it => if (it.isEmpty) "0" else it)
然后你可以像這樣使用它 total_deaths = cells(4).toDouble
順便說一句,null在scala中通常指的是“空指標”。
在您的情況下,您沒有任何“空指標”,您只有“空字串”
uj5u.com熱心網友回復:
你可以做的是這樣的:
for (line <- rf) {
val data = line.split(',').toList.map(str => Option(str).filter(_.nonEmpty))
}
這種方式data將是List[Option[String]]空值None,然后您可以使用模式匹配來額外獲取您想要的資料。
uj5u.com熱心網友回復:
如果您必須在需要的地方應用更改:
//line.(**How to replace the null with 0?**)
你可以這樣做:
val line2 = if (line.trim().isEmpty) "," else line
然后在其他地方使用 line2。
作為一個方面的事情,如果你想要做的事多階,與.toList取代.toArray和看看如何map,filter,sum等作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358564.html
