这是有关countWords的示例。 (斯卡拉)
[origin]
def countWords(text: String): mutable.Map[String,Int] = {
val counts = mutable.Map.empty[String,Int]
for (rawWord <- text.split("[,!.]+")) {
val word = rawWord.toLowerCase
val oldCount =
if (counts.contains(word)) counts(word)
else 0
counts += (word -> (oldCount + 1))
}
return counts
}
[my code]
here is my code.
def countWords2(text: String):mutable.Map[String,Int]s
text.split("[,!.]").foreach(word =>
val lowWord = word.toLowerCase()
val oldCount = if (counts.contains(lowWord)) counts(lowWord) else 0
counts += (lowWord -> (oldCount + 1))
)
return counts
}
我尝试将“ for()”句子转移到“ foreach”,但收到“无法解析符号”错误消息。 在这种情况下如何使用foreach?