Scala例题

package Scala3

import scala.collection.mutable.ListBuffer

//1
case class Book(var ID:String,var bookName: String, var author: String,var price: Double,var number:Int) {

}
object timu {
  def main(args: Array[String]): Unit = {
    //2
    val BookList=ListBuffer[Book]()
    //3
    BookList+=new Book("001","西游记","吴承恩",23.4,100)
    BookList+=new Book("002","星际远航:宇宙边缘的探索者"," 林羽",69,100)
    BookList+=new Book("003","时间裂缝:错乱时空的冒险","苏晓",78,28)
    println(BookList)
    //4.添加一本书
    val book1=Book("002","星际远航:宇宙边缘的探索者"," 林羽",69,100)
//    //如果已经包含这本书,直接去修改数量
//    for(b<-BookList){
      println(b.ID)
//      if(b.ID==book1.ID){//同一本书
        println(b)
//        b.number+=book1.number
//        println(b)
//
//      }
//    }
    //查找,是否ID为book.ID的元素,找到就返回,没有找到,就返回None
    val rs=BookList.find(_.ID==book1.ID)
    println(rs)
    if(rs.isEmpty){
      println("没有")
      BookList+=book1
    }else{
      println("有")
      val s=rs.get//拿出具体的数据
      s.number+=book1.number//数量增加
    }
    //5,根据名称去查询
    var bookName="三体"
    val rs1=BookList.find(_.bookName==bookName)
    if(rs1.isEmpty){
      println(s"《$bookName》不存在")
    }else{
      println(s"《$bookName》存在")
    }

    //6.删除指定书名的书
    bookName = "三体"
    val rs2 = BookList.find(_.bookName == bookName)
    if (rs2.isEmpty) {
      println(s"《$bookName》不存在,删除失败")
    } else {
      println(s"《$bookName》存在,删除成功")
      BookList-=rs2.get
    }
    //7.删除指定ID
    var id = "三体"
    val rs3 = BookList.find(_.ID == id)
    if (rs3.isEmpty) {
      println(s"id:$id 不存在,删除失败")
    } else {
      println(s"id:$id 存在,删除成功")
      BookList -= rs3.get
    }

    //8.价格顺序
    val or=BookList.sortWith((a,b)=>a.price>b.price)
    println(or)
    //9.遍历
    BookList.foreach(el=>{
      println(s"书名:${el.bookName},作者:${el.author},价格:${el.price},数量:${el.number}")

    })
    //10.计算全部金额
    var sum:Double=0
    BookList.foreach((w=>{
      sum+=(w.number*w.price)
    }))
    println(s"总的金额是:${sum}")



    }


}
上一篇:Jailbreaking ChatGPT via Prompt Engineering: An Empirical Study


下一篇:内网域环境、工作组、局域网等探针方案