score

71 阅读1分钟

image.png

object score01 {

  def main(args: Array[String]): Unit = {
    // printf("小关,100,80,90".split(",")(1) )

    // 1. 读入文件 迭代器
    val lines = scala.io.Source.fromFile("score.txt").getLines()

    lines.next() // 跳过第一行

    while(lines.hasNext){
      val line = lines.next()
      // 字符串拆分
      val li = line.split(",")
      val name = li(0)
      val yuwen = li(1)

      println(s"${name}, ${yuwen}")
    }
  }
}

image.png

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}")
    })
  }
}

image.png