object score01 {
case class Stu(name:String, yuwen:Double, shuxue:Double,yingyu:Double)
def main(args: Array[String]): Unit = {
// 0. 创建一个可变List
val stuList = scala.collection.mutable.ListBuffer[Stu]()
// 1. 读文件 迭代器
val lines = scala.io.Source.fromFile("score.txt").getLines()
lines.next() // 跳过第一行
while(lines.hasNext){
val line = lines.next()
// 字符串拆分
val li = line.split(",")
stuList += Stu(li(0), li(1).toDouble, li(2).toDouble, li(3).toDouble)
}
// 读入数据结果
println("读入数据结果")
stuList.foreach(stu => {
val total = stu.yuwen + stu.yingyu + stu.shuxue
val avg = total / 3
println(s"${stu.name}, 总分: ${total}, 平均分: ${avg}")
})
}
}
1. 样例类(Case Class)
scala
case class Student(name: String, chinese: Double, math: Double, english: Double)
- 样例类是 Scala 中用于封装数据的便捷方式,自动生成
equals、hashCode、toString等方法; - 支持直接通过
Student(参数)创建对象,无需new关键字。
2. 可变集合 ListBuffer
scala
val studentList = scala.collection.mutable.ListBuffer[Student]()
- 相比于不可变 List,ListBuffer 支持高效的动态添加元素(
+=操作); - 适合文件读取过程中逐步收集数据的场景。
3. 文件读取方式
scala
val lines = scala.io.Source.fromFile("score.txt").getLines()
Source.fromFile获取文件数据源,getLines()返回行迭代器(Iterator);- 迭代器是懒加载的,不会一次性加载所有行到内存,适合处理大文件。
4. 异常处理
- 添加
try-catch捕获文件不存在、数据格式错误、类型转换失败等异常; - 增强程序的健壮性,避免因数据问题导致程序崩溃。