cace class的实训题

24 阅读1分钟

学习了case class,同学们也会合理运用了吧,我们来完成以下的题目吧,做出一个完美的一个题目来检验一下自己👌👌👇👇👇

可以参考以下代码,自己完成题目哦!!!!!!!❤️❤️❤️ image.png 代码:

package caseclass1

import scala.collection.mutable.ListBuffer

object class4 {
  // 1,
  case class  Book(id:Int,name:String,author:String,price:Double,var amount:Int)

  def main(args: Array[String]): Unit = {
    // 2 ,
    val BookList: ListBuffer[Book] = ListBuffer()
    //3
    val book1 = Book(1,"语言文学艺术","梦语",20.2,1)
    val book2 = Book(2,"怎么变成有钱人?","梦语",50,2)
    val book3 = Book(3,"悄悄靠近你","梦语",55,3)
    BookList += book1
    BookList += book2
    BookList += book3
    //4
    //  val book4 = Book(3,"悄悄靠近你","梦语",55,3)
    val book4= Book(4,"悄悄靠近你完结篇","梦语",55,10)
    val rst4 = BookList.find(ele=>ele.id == book4.id)
    if(rst4.isDefined) { // 修改数量
      rst4.get.amount = rst4.get.amount + book4.amount
    } else {
      BookList += book4
    }
    //5
    var bookName = "怎么变成有钱人?"
    val rst0 = BookList.find(ele => ele.name == bookName)
    if(rst0.isDefined){
      println(s"${bookName} 》 不存在")
    } else {
      println(s"${bookName} 》 不存在")
    }
    //6,删除书名是 语言文学艺术 书
    bookName = "语言文学艺术"
    val rst1 = BookList.find(ele=>ele.name==bookName)
    if (rst1.isDefined){
      BookList -= rst1.get
      println(s"删除书名是${bookName}的书成功")
    } else {
      println(s"没有找到书名是:${bookName}的书")
    }

    //7删除id为1的书
    val id = 1
    val rst2= BookList.find(ele=>ele.id==id)
    if(rst2.isDefined) {
      BookList -= rst2.get
      println(s"删除id=${id}的书成功")
    } else {
      println(s"没有找到id=${id}的书")
    }
    // 8 sortWith
    val newList = BookList.sortWith((a,b) =>{
      a.price > b.price
    })

    // 9
    newList.foreach(ele =>{
      println(s"${ele.id} ${ele.name} ${ele.price} ${ele.amount}本")
    })
    //10
    var totalPrice= 0.0
    newList.foreach(ele => {
      totalPrice += ele.price * ele.amount
    })
    println(s"总价格:${totalPrice}")
  }

}