姓名,语文,数学,英语 张伟,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
package test1
import java.io.PrintWriter
import scala.collection.mutable.ListBuffer
import scala.io.Source
case class Student(name:String,yuwen:Double,shuxue:Double,yingyu:Double,total:Double,avg:Double)
//案例:统计成绩
object test {
def main(args: Array[String]): Unit = {
//可变List,保存所有的学生数据
val studentList = ListBuffer[Student]()
//1.按行读入文件
val source = Source.fromFile("score.txt")
val it = source.getLines()// 迭代器
it.next() // 跳过第一行
while (it.hasNext){
val arr = it.next().split(",") //中文的逗号
val name = arr(0)
val yuwen = arr(1).toDouble
val shuxue = arr(2).toDouble
val yingyu = arr(3).toDouble
val total = yuwen + shuxue + yingyu //计算得分
val avg = total / 3 //计算平均分
val s = Student(name,yuwen,shuxue,yingyu,total,avg)
studentList += s
}
source.close()
// 计算单科总分
var avgYuwen:Double = 0
var avgShuxue:Double = 0
var avgYingyu:Double = 0
studentList.foreach(s=>{
avgYuwen += s.yuwen
avgShuxue += s.shuxue
avgYingyu += s.yingyu
})
println("语文平均分",avgYuwen / studentList.length)
println("数学平均分",avgYuwen / studentList.length)
println("英语平均分",avgYuwen / studentList.length)
//总分的前三名
//思路:1.对所有的同学按总分从高到低排名
val list1 = studentList.sortWith((a,b)=>a.total > b.total).slice(0,3)
println("总分从高到低排名前三:")
list1.foreach(println)
val list2 = studentList.sortWith((a,b)=>a.yuwen > b.yuwen).slice(0,3)
println("语文从高到低排名前三")
list2.foreach(println)
val list3 = studentList.sortWith((a,b)=>a.shuxue > b.shuxue).slice(0,3)
println("数学从高到低排名前三")
list3.foreach(println)
val list4 = studentList.sortWith((a,b)=>a.yingyu > b.yingyu).slice(0,3)
println("英语从高到低排名前三")
list4.foreach(println)
//写入文件
val writer = new PrintWriter("统计成绩的结果") //创建一个全新的文件
writer.println("姓名,语文,数学,英语,总分,平均分")
studentList.foreach(s => {
val avg = String.format("%.1f",s.avg) //只保留一位有效数字
writer.println(s"${s.name},${s.yuwen},${s.shuxue},${s.yingyu},${s.total},${avg}")
})
writer.println("-"*48)
// 总分前三名
list1.foreach(s => {
val avg = String.format("%.1f",s.avg) //只保留一位有效数字
writer.println(s"${s.name},${s.yuwen},${s.shuxue},${s.yingyu},${s.total},${avg}")
})
writer.println("-"*40)
writer.close() //关闭文件
}
}