Scala关于成绩的常规操作

复制代码
score.txt中的数据:

姓名,语文,数学,英语

张伟,87,92,88

李娜,90,85,95

王强,78,90,82

赵敏,92,88,91

孙涛,85,82,89

周梅,88,87,93

吴刚,80,85,86

郑洁,91,89,94

陈晨,83,84,88

林峰,86,91,87

复制代码
Scala 复制代码
import scala.collection.mutable.ListBuffer
import scala.io.Source
//1.迭代器,跳过第一个元素
//2.把字符串转成数字
//3.如何判断一个正整数是否可以被3整除? (1+2+3) % 3 == 0

case class Student(name:String,yuwen:Int,shuxue:Int,yingyu:Int,total:Int,avg:Int)
//成绩分析
object Test {
  def main(args: Array[String]): Unit = {
    //0.定义一个空列表
    val list = ListBuffer[Student]()
    //1.读入成绩,按行读取,跳过第一个元素
    val it = Source.fromFile("score.txt").getLines().drop(1)
    var shuxuezongfen = 0
    while (it.hasNext) {
      val content = it.next()
      //使用中文的逗号去拆分字符串
      var arr = content.split(",")
      val name = arr(0)
      val yuwen = arr(1).toInt
      val shuxue = arr(2).toInt
      val yingyu = arr(3).toInt
      val total = yuwen + shuxue + yingyu
      val avg = total / 3

      shuxuezongfen += shuxue
      //创建一个对象
      list += Student(name, yuwen, shuxue, yingyu, total, avg)
    }
    //数学平均分
    println("数学平均分",shuxuezongfen / list.length)
    //根据总分进行排序
    val orderList = list.sortWith((a,b)=>a.total>b.total).slice(0,3)
    //打印结果
    orderList.foreach(s=>println(s"姓名:${s.name},总分:${s.total}"))

    //根据数学成绩进行排序
    list.sortWith((a,b)=>a.shuxue>b.shuxue)
    .foreach(s=> println(s"姓名:${s.name},数学:${s.shuxue},总分:${s.total}"))
  }
}
相关推荐
与仪共舞1 天前
罗德与施瓦茨 NRP18S|三路二极管射频功率传感器
scala·数据库架构
howard20055 天前
1.8.3 掌握Scala类与对象 - Scala基本骨架方法
scala·基本骨架方法
howard20056 天前
1.9 掌握Scala抽象类与特质
scala·抽象类·特质
howard20057 天前
1.8.2 掌握Scala类与对象 - 单例对象与伴生对象
scala·伴生对象·单例对象
howard20059 天前
1.7.1 掌握Scala函数 - 声明Scala函数
scala·声明scala函数·显式声明·隐式声明
howard200511 天前
1.6.4 掌握Scala数据结构 - 元组
scala·元组
howard200511 天前
1.6.5 掌握Scala数据结构 - 集合
scala·集合
蓝眸少年CY12 天前
Scala - 基础教程
开发语言·后端·scala
howard200512 天前
1.6.3 掌握Scala数据结构 - 映射
scala·可变映射·不可变映射
亿牛云爬虫专家13 天前
拒绝代理池雪崩:Scala + Akka 构建高并发的路由分发实战
scala·高并发·爬虫代理·代理ip·隧道代理·akka actor 模型·api代理