3. 统计学生成绩



object test3 {
  case class student(id: String, gender: String, score: Map[String, Int])

  //读取文件的方法:
  def inputStudentList(filename: String): List[student] = {
    // 读取文件并按行进行切割
    var lines = scala.io.Source.fromFile(filename).getLines.toList
    // 获取表头 :课程名 drop(2) 意思是去除前两个 即id 跟 gender
    val header = lines.head.split("\\s+").drop(2)
    // 解析每一行学生的信息
    val students = lines.tail.map { line =>
      val Array(id, gender, scores@_*) = line.split("\\s+")
      val scoreMap = header.zip(scores.map(_.toInt)).toMap
      student(id, gender, scoreMap)
    }
    students
}
  //计算 传入三个值 一个学生集合  一个课程名  一个性别筛选条件
  def calculateScore(student:List[student],course:String,genderFilter: Option[String] = None): (Double,Double,Double) ={
    val filterStudents = genderFilter match {
      case Some(gender)  =>student.filter(_.gender == gender)
      case None => student
    }
    val scores = filterStudents.flatMap(_.score.get(course))
    val average = scores.sum.toDouble / scores.size
    val min = scores.min
    val max = scores.max
    (average,min,max)
  }
  def main(args: Array[String]): Unit = {
    val students = inputStudentList("G:\\scalaCode\\untitled1\\src\\student1.txt")
    val header = students.head.score.keys.toList
    val genders = List("male", "female")
    println(s"course\taverage\tmin\t\tmax")
    for (course <- header) {
      val (average, min, max) = calculateScore(students, course)
      println(f"$course\t${"%.2f".format(average)}\t${"%.2f".format(min)}\t${"%.2f".format(max)}")
    }
    for (gender <- genders) {
      println(s"\ncourse\taverage\tmin\t\tmax ($gender)")
      for (course <- header) {
        val (average, min, max) = calculateScore(students, course, Some(gender))
        println(f"$course\t${"%.2f".format(average)}\t${"%.2f".format(min)}\t${"%.2f".format(max)}")

      }
    }
  }
}

posted @ 2024-02-01 21:11  会秃头的小白  阅读(7)  评论(0编辑  收藏  举报