- // 如果有一个字符串数组:
- // 统计词频
- val arr1 = Array("thank","you","very","much","thank","very")
- val m1 = scala.collection.mutable.Map[String, Int]()
- arr1.foreach(word => {
- // 检查是否出现过?
- if( m1. contains( 1 )) {
- // 把票数+1
- m1(word) += 1
- } else{
- // 票数为1
- m1(word) = 1
- }
- })
- m1.foreach { case (word, cishu) => println(s"${word}: ${cishu}")}
复制代码
- // 对于m1,它是一个Map(thank: 10, is: 5),现在需要对它进行排序,把出现次数最多的放在前面,然后再输出
- // (rhank, 10)
- // 只要排序之后的结果的前15个? 在List中取出前15个?
- val sortedM1 = m1.toList.sortWith((a,b)=>a._2 > b._2).filter(a=>a._1.length>2).slice(0,15)
- // 输出排序后的1Map
- sortedM1.foreach { case (word,cisu) => println(s"${word}: ${cishu}")}
- // 把结果保存到一个新的文件中:
- writer.println("统计的结果是:")
- sortedM1.foreach { case (word, cishu) => writer.println(s"${word}: ${cishu}") }
- writer.close() // 结束写入
- }
- }
- }
复制代码  


- package test33
- // 1、迭代器,跳过第一个元素
- // 2、把字符串转成数字
- // 3、 如何判断一个1正整数是否可以被3整除? (1+2+3) % 3 == 0
- import scala.io.Source
- // 成绩分析
- object test {
- def main(args: Array[String]): Unit = {
- // 0、定义一个空列表
- val list = ListBuffet[Student]()
- // 1、读入成绩 - 按行去读取 - 跳过的一个元素
- val it = Source.formFile("score.txt").getLines().drop(1)
- while(it.hasNext){
- val content = it.next()
- // 使用中文的逗号去拆分字符串
- var arr = content.split(",")
- val name = arr(0)
- val yvwen = arr(1).toInt
- val shuxue = arr(2).toInt
- val yingyv = arr(3).toInt
- val total = yvwen + shuxue + yingyv
- val avg = total / 3
- // 创建一个对象
- list += Student(name, yvwen, shuxue, yingyv, total, avg)
- }
- // 根据总分进行排序
- val orderList = list.sortWith((a, b) => a.total > b.total)
- // 打印结果
- orderList.foreach(s => println(s"姓名:${s.name}, 总分:${s.total}"))
- // 根据数学进行排序
- list.sortWith((a, b) => a.shuxue > b.shuyxue).foreach(s => println(s"姓名:${s.name},数学:${s.shuxue},总分:${s.total}"))
- }
- }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |