读取
姓名,语文,数学,英语
张伟,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
这个文件,按行读入,计算每个同学的总分和平均分,
每个科目的平均分,总分的前三名,单科的前三名,
把结果写入文件
import java.io.PrintWriter
import scala.io.Source
import scala.collection.mutable.ListBuffer
case class Student(name:String, chinese:Double, math: Double, english: 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 chinese = arr(1).toDouble
val math = arr(2).toDouble
val english = arr(3).toDouble
val total =chinese + math + english //计算总分
val avg =total/3 //计算平均分
// println(name, chinese, math, english,total,avg)
val s = Student(name, chinese, math, english,total,avg)
studentList += s
}
source.close()
//计算单科总分
var avgchinese : Double = 0
var avgmath: Double = 0
var avgenglish: Double = 0
studentList.foreach(s =>{
avgchinese += s.chinese
avgmath += s.math
avgenglish += s.english
})
println("语文平均分:",avgchinese / studentList.length)
println("数学平均分:",avgmath / studentList.length)
println("英语平均分:",avgenglish / 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.chinese > b.chinese).slice(0,3)
println("语文前三:")
list2.foreach(println)
val list3 = studentList.sortWith((a,b)=> a.math > b.math).slice(0,3)
println("数学前三:")
list3.foreach(println)
val list4 = studentList.sortWith((a,b)=> a.english > b.english).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.chinese},${s.math},${s.english},${s.total},${s.avg}")
})
writer.println("-"*40)
writer.println("总分的前三")
//总分的前三
list1.foreach(s =>{
val avg = String.format("%.1f", s.avg) //只保留一位有效数字
writer.println(s"${s.name},${s.chinese},${s.math},${s.english},${s.total},${s.avg}")
})
writer.println("-"*40)
writer.println("语文的前三")
//语文的前三
list2.foreach(s => {
val avg = String.format("%.1f", s.avg) //只保留一位有效数字
writer.println(s"${s.name},${s.chinese},${s.math},${s.english},${s.total},${s.avg}")
})
writer.println("-" * 40)
writer.println("数学的前三")
//数学的前三
list2.foreach(s => {
val avg = String.format("%.1f", s.avg) //只保留一位有效数字
writer.println(s"${s.name},${s.chinese},${s.math},${s.english},${s.total},${s.avg}")
})
writer.println("-" * 40)
writer.println("英语的前三")
//英语的前三
list4.foreach(s => {
val avg = String.format("%.1f", s.avg) //只保留一位有效数字
writer.println(s"${s.name},${s.chinese},${s.math},${s.english},${s.total},${s.avg}")
})
writer.println("-" * 40)
writer.close() //关闭文件
}
}