1.准备一个空的List
2.读取文件—按行读取
3.添加学生到List
对有序的列表,从前开始向后一一比较
(1).如果当前的分数不等于预设分数,则名次+1,更新预设分数
(2).如果当前的分数等于预设分数,则名次不变
4.排名
实例操作代码如下:
import java.io.PrintWriter
import scala.collection.mutable.ListBuffer
import scala.io.Source
case class Student(name:String,yuwen:Int,shuxue:Int,yingyu:Int,java:Int,zongfen: Int,pinjunfen:Int,var mingci:Int)
object test {def main(args: Array[String]): Unit = {// 0. 准备一个空的Listval list = ListBuffer[Student]()// 1. 读入文件 - 按行读取// drop(1) 让迭代器跳过一个元素,因为第一行是表头,把第一行跳过去val it = Source.fromFile("score.txt").getLines().drop(1)// 跳过一个元素while(it.hasNext){val arr = it.next().split(",")val total = arr(1).toInt + arr(2).toInt + arr(3).toInt + arr(4).toInt// 3. 添加学生到Listlist +=Student(arr(0), arr(1).toInt,arr(2).toInt, arr(3).toInt, arr(4).toInt,total,total / 3, 0)}val orderList = list.sortWith((a, b) => a.zongfen > b.zongfen)// 对有序的列表,从前开始向后一一比较:// (1) 如果当前的分数不等于预设分数,则名次 +1, 更新预设分数// (2) 如果当前的分数等于预设分数,则名次不变var curScore = -1var mingci = 0;for (elem <- orderList) {if (elem.zongfen != curScore) {mingci += 1elem.mingci = mingcicurScore = elem.zongfen} else {elem.mingci = mingci}}// 4. 排名// 根据总分排名,取前三名val li1 = list.sortWith((a,b)=>a.zongfen > b.zongfen)//li1.foreach(println)// 按语文排名,取前三名val li2 = list.sortWith((a, b) => a.yuwen > b.yuwen).slice(0, 3)li2.foreach(println)// 5. 写入val writer = new PrintWriter("排名之后的结果.txt")// 所有的成绩list.foreach(s => {writer.println(s"姓名:${s.name}, 名次:${s.mingci},语文: ${s.yuwen}, 数学: ${s.shuxue}, 英语: ${s.yingyu}, java: ${s.java}, 总分:${s.zongfen}, 平均分:${s.pinjunfen}")})writer.println("-"*40)li1.foreach(s => {writer.println(s"姓名:${s.name}, 总分:${s.zongfen}")})writer.println("-" * 40 + "语文前三名")li2.foreach(s => {writer.println(s"姓名:${s.name}, 语文: ${s.yuwen},总分:${s.zongfen}")})writer.close() // 结束输出}
}
总分排名代码如下:
import scala.collection.mutable.ListBuffer
object test_order {def main(args: Array[String]): Unit = {case class Student(name:String,zongfen:Int,var mingci:Int)val list=ListBuffer[Student]()
// 并列list+=Student("孙涛",90,0)list+=Student("林峰",102,0)list+=Student("周梅",101,0)list+=Student("郑洁",105,0)list+=Student("陈晨",90,0)list+=Student("吴刚",102,0)// 对list进行排序,按总分排序val orderList=list.sortWith((a,b)=>a.zongfen>b.zongfen)// 对有序的列表,从前开始向后一一比较:
// (1)如果当前的分数不等于预设分数,则名次+1,更新预设分数
// (2)如果当前的分数等于预设分数,则名次不变var curScore = -1var mingci=0;for(elem<-orderList){if(elem.zongfen!=curScore){mingci+=1elem.mingci=mingcicurScore=elem.zongfen}else{elem.mingci=mingci}}list.foreach(println)}
}