import scala.collection.mutable.ListBuffer
//1.使用 case class 创建图书信息类 Book:
case class Book(ID:String,bookName:String,author:String,price:Double,var amount:Int)
object demo1 {
def main(args: Array[String]): Unit = {
//2.创建一个名为 BookList 的可变 List:
val BookList = ListBuffer[Book]()
//.3初始化三本不同的书:
BookList += Book("001","book1","author1",100,10)
BookList += Book("002","book2","author2",200,20)
BookList += Book("003","book3","author3",300,30)
//4.添加一本书
val book1 = Book("002","b","b2",150,5)
//如果已经包含这本书,直接去修改数量
val rs = BookList.find(_.ID == book1.ID)
if(rs.isEmpty){
println("没有")
BookList += book1
}else{
println("有")
val s = rs.get //拿出具体的数据
s.amount += book1.amount //数量增加
}
//5.根据名称去查询
var bookName = "book4"
val rs1 = BookList.find(_.bookName == bookName)
if(rs1.isEmpty)
println(s"《$bookName》 不存在")
else
println(s"《$bookName》 存在")
//6.删除指定书名的书
bookName = "book1"
val rs2 = BookList.find(_.bookName == bookName)
if (rs2.isEmpty)
println(s"《$bookName》 不存在,删除失败")
else {
println(s"《$bookName》 存在,删除成功")
BookList -= rs2.get
}
//7.删除指定ID的书
val ID = "002"
val rs3 = BookList.find(_.ID == ID)
if(rs3.isEmpty)
println(s"id:$ID 不存在,删除失败")
else {
println(s"id:$ID 存在,删除成功")
BookList -= rs3.get
}
//8.价格排序
val orderList = BookList.sortWith((a,b) => a.price>b.price)
//9.遍历
orderList.foreach(el =>{
println(s"书名${el.bookName},作者${el.author},价格${el.price},数量${el.author}")
})
//10.计算全部的金额
var sum:Double = 0;
BookList.foreach((el =>{
sum += (el.amount * el.price)
}))
println(s"总金额是:${sum}")
}
}
标签:el,val,Scala,bookName,练习,BookList,println,ID
From: https://blog.csdn.net/2402_83403264/article/details/143718705