Scala
复制代码
import scala.collection.mutable.ListBuffer
case class Book(id:String,bookName:String,author:String,price:Double,var amount:Int)
object p4 {
def main(args: Array[String]): Unit = {
//2
val BookList = ListBuffer[Book]()
//3
BookList += Book("001", "b1", "a1", 23, 42)
BookList += Book("002", "b2", "a2", 55, 77)
BookList += Book("003", "b3", "a3", 82, 11)
println(BookList)
//4
val book1 =Book("004", "b4", "a4", 30, 24)
//如果已经包含这本书,直接去修改数量
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="b4"
val rs1=BookList.find(_.bookName==bookName)
if(rs1.isEmpty)
println(s"《$bookName》不存在")
else
println(s"《$bookName》存在")
//6
bookName = "b1"
val rs2 = BookList.find(_.bookName == bookName)
if (rs2.isEmpty)
println(s"《$bookName》不存在,删除失败")
else {
println(s"《$bookName》存在,删除成功")
BookList-=rs2.get
}
//7
val id = "002"
val rs3=BookList.find(_.id==id)
if(rs3.isEmpty)
println(s"$id 不存在,删除失败")
else {
println(s"$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.amount}")
})
//10
var sum:Double=0
BookList.foreach((el=>{
sum+=(el.amount*el.price)
}))
println(s"总的金额是:${sum}")
}
}