案例:统计成绩
1.按行读入文件
import scala.io.Source
//案例:统计成绩object dd1 {def main(args: Array[String]): Unit = {//1.按行读入文val source = Source.fromFile("score.txt")val it = source.getLines()//迭代器it.next()//跳过第一行while (it.hasNext){println(it.next())}source.close()}}
2.处理数据
while (it.hasNext){val arr = it.next().split(",")val name = arr(0)val yuwen = arr(1).toDoubleval shuxue = arr(2).toDoubleval yingyu = arr(3).toDoubleval total=yuwen+shuxue+yingyuval avg = total / 3val s = Student(name,yuwen,shuxue,yingyu,total,avg)studentList += s}source.close()//计算单科总分var avgyuwen:Double = 0var avgshuxue:Double = 0var avgyingyu:Double = 0studentList.foreach(s=>{avgyuwen +=s.yuwenavgshuxue +=s.shuxueavgyingyu +=s.yingyu})println("语文平均分",avgyuwen / studentList.length)println("数学二平均分",avgshuxue / studentList.length)println("英语平均分",avgyingyu / studentList.length)}}
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 dd1 {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).toDoubleval shuxue = arr(2).toDoubleval yingyu = arr(3).toDoubleval total=yuwen+shuxue+yingyuval avg = total / 3val s = Student(name,yuwen,shuxue,yingyu,total,avg)studentList += s}source.close()//计算单科总分var avgyuwen:Double = 0var avgshuxue:Double = 0var avgyingyu:Double = 0studentList.foreach(s=>{avgyuwen +=s.yuwenavgshuxue +=s.shuxueavgyingyu +=s.yingyu})println("语文平均分",avgyuwen / studentList.length)println("数学二平均分",avgshuxue / studentList.length)println("英语平均分",avgyingyu / 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.yingyu>b.yingyu).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.yuwen> b.yuwen).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("-"*40)//总分前三名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()}}