系列文章目录
前言
这学期开了《Spark编程基础》,需要用到Scala语言,书上写的比较简单,本着学一门语言就应该尽量往深处学的想法,到图书馆借了一本《快学Scala》,英文名《Scala for the Impatient》,争取每周看完两章,并将相应练习写成博客。
由于最近在参加几个竞赛,时间不够充裕,每周完成一章练习。
练习
1.设置一个映射,其中包含你想要的一些装备,以及它们的价格。然后构建另一个映射,采用同一组键,但在价格上打9折。
object Test {
def main(args: Array[String]): Unit = {
val equipment = Map("bag" -> 99, "clothes" -> 188, "table" -> 240)
//进行迭代映射,将价格乘以0.9
val equipment1 = for((e,p) <- equipment) yield (e,0.9 * p)
println(equipment)
println(equipment1)
}
}
2.编写一段程序,从文件中读取单词。用一个可变映射来清点每一个单词出现的频率。读取这些单词的操作可以使用java.util.Scanner:
val in = new java.util.Scanner(new java.io.File("myfile.txt"))
while (in.hasNext()) 处理 in.next()
或者翻到第9章看看更Scala的做法。最后,打印出所有单词和它们出现的次数。
文件内容为:
Most kids like animals Girls like cats, and boys like dogs However, my favorite animal is the horse The horses are strong, not like the tame cats or puppy dogs. They look wild and hard to get close Yet, they will be very timid and friendly after they get to know you Horses remember the way home.
They are also faithful to their masters. They even understand what you are trying to tell them. I have heard many stories about how a horse saved his master’s life That is also the reason why I love horses. They never betray you.
import java.io.File
import java.uti