据文件2016phonelocation,编写程序实现功能:运行程序,用户输入任意省份,输出这个省份号码段的个数,电信、移动、联通各占多少个。
读取文件 & 嵌套Map使用
/**
* 输入省份查找对应省份 电信联通移动三家运营商数据
* 缺点:虚拟运营商找不到,每次都需加载数据时空消耗大
* @param pro
*/
def findPhone(pro: String): Unit = {
var a: Int = 0
var b: Int = 0
var c: Int = 0
var sum: Int = 0
for (line <- Source.fromFile("2016phonelocation.txt").getLines(); if line.contains(pro)) {
sum += 1
if (line.contains("电信")) a += 1
if (line.contains("移动")) b += 1
if (line.contains("联通")) c += 1
}
println("新疆省份号码个数为\t:\t" + sum
+ "\n中国电信号码个数为\t:\t" + a
+ "\n中国移动号码个数为\t:\t" + b
+ "\n中国联通号码个数为\t:\t" + c)
}
/**
* 预处理数据存入Map映射中 (省份->(运营商->数量))
* @return
*/
def findPhone2(): Map[String, Map[String, Int]] = {
var res: Map[String, Map[String, Int]] = Map()
for (line <- Source.fromFile("2016phonelocation.txt").getLines()) {
var tmp = line.split(',') // 2 省 4 运营商
if (res.contains(tmp(2))) // 省数据
if (res(tmp(2)).contains(tmp(4))) res(tmp(2))(tmp(4)) += 1
else res(tmp(2)) += (tmp(4) -> 1)
else res += (tmp(2) -> Map(tmp(4) -> 1))
}
return res
}