文件读写-成绩分析

11 阅读1分钟
import scala.io.Source 
import scala.collection.mutable.ListBuffer
// 定义样例类,封装学生成绩(name:姓名,yuwen/shuuxue/yingyu:各科成绩)
case class Student(name: String, yuwen: Double, shuxue: Double, yingyu: Double)
/**
* 组装学生成绩对象列表 
*/ 
object StudentDataAssemble { 
def main(args: Array[String]): Unit = { 
// 初始化可变列表,存储Student对象
val stuList = new ListBuffer[Student]() 
val source = Source.fromFile("input.txt")
try {
// 遍历每行数据,拆分并创建对象 
for (line <- source.getLines()) { 
// 跳过空行
if (line.nonEmpty) { 
// 按逗号拆分字段(需保证文件格式为:姓名,语文,数学,英语) 
val fields = line.split(",")
// 校验字段数量,避免格式错误导致异常
if (fields.length == 4) {
val name = fields(0).trim 
// 字符串转Double,处理非数字异常
val yuwen = try { fields(1).trim.toDouble } catch { case _: Exception => 0.0 }
val shuxue = try { fields(2).trim.toDouble } catch { case _: Exception => 0.0 } 
val yingyu = try { fields(3).trim.toDouble } catch { case _: Exception => 0.0 } 
// 添加到列表 
stuList += Student(name, yuwen, shuxue, yingyu)
} else {
println(s"数据格式错误,跳过此行:$line")
}
} 
} 
// 打印验证结果
println("\n✅ 组装的学生对象列表:")
stuList.foreach(stu => println(s"姓名:${stu.name},语文:${stu.yuwen},数学:${stu.shuxue},英语:${stu.yingyu}")) 
} catch { case ex: Exception => println(s"组装数据失败:${ex.getMessage}") 
} finally { 

source.close() 
} 
} 
}