package caseclass
object case03 {
case class Book(id: String, name: String, author: String, price: Double, amount: Int)
object Case03 {
def main(args: Array[String]): Unit = {
val bookList = scala.collection.mutable.ListBuffer[Book]()
val book1 = Book("1", "无羁", "墨香铜臭", 80.0, 10)
val book2 = Book("2", "某某", "木苏里", 50.0, 9)
val book3 = Book("3", "全球高考", "木苏里", 60.0, 5)
bookList ++= List(book1, book2, book3)
println("=== 初始化后的图书列表 ===")
printBookList(bookList)
println("\n=== 尝试添加已存在的书(ID=1,无羁)===")
val existingBook = Book("1", "无羁", "墨香铜臭", 80.0, 3)
addBook(bookList, existingBook)
println("添加后的图书列表:")
printBookList(bookList)
println("\n=== 查询图书:《某某》===")
val targetName = "某某"
val isExist = checkBookByName(bookList, targetName)
println(s"图书《$targetName》是否存在:$isExist")
println("=== 查询图书:《撒野》===")
val targetName2 = "撒野"
val isExist2 = checkBookByName(bookList, targetName2)
println(s"图书《$targetName2》是否存在:$isExist2")
println("\n=== 删除书名:《全球高考》===")
deleteBookByName(bookList, "全球高考")
println("删除后的图书列表:")
printBookList(bookList)
println("\n=== 删除 ID=2 的书 ===")
deleteBookById(bookList, "2")
println("删除后的图书列表:")
printBookList(bookList)
println("\n=== 按价格从高到低排序 ===")
val sortedList = bookList.sortWith((a, b) => a.price > b.price)
printBookList(sortedList)
println("\n=== 计算总金额 ===")
val totalAmount = calculateTotalAmount(bookList)
println(s"所有图书的总金额:$totalAmount 元")
}
def printBookList(books: scala.collection.mutable.ListBuffer[Book]): Unit = {
if (books.isEmpty) {
println("列表为空")
return
}
books.foreach(book => {
println(s"ID:${book.id} | 书名:${book.name} | 作者:${book.author} | 价格:${book.price}元 | 数量:${book.amount}本")
})
}
def addBook(books: scala.collection.mutable.ListBuffer[Book], newBook: Book): Unit = {
books.find(_.id == newBook.id) match {
case Some(existBook) =>
val updatedBook = existBook.copy(amount = existBook.amount + newBook.amount)
books -= existBook
books += updatedBook
println(s"图书《${newBook.name}》已存在,数量更新为:${updatedBook.amount}本")
case None =>
books += newBook
println(s"图书《${newBook.name}》新增成功")
}
}
def checkBookByName(books: scala.collection.mutable.ListBuffer[Book], name: String): Boolean = {
books.exists(book => book.name.equalsIgnoreCase(name))
}
def deleteBookByName(books: scala.collection.mutable.ListBuffer[Book], name: String): Unit = {
val toDelete = books.filter(_.name.equalsIgnoreCase(name))
if (toDelete.nonEmpty) {
books --= toDelete
println(s"成功删除 ${toDelete.size} 本同名图书:《$name》")
} else {
println(s"未找到书名《$name》的图书,删除失败")
}
}
def deleteBookById(books: scala.collection.mutable.ListBuffer[Book], id: String): Unit = {
books.find(_.id == id) match {
case Some(book) =>
books -= book
println(s"成功删除 ID=$id 的图书:《${book.name}》")
case None =>
println(s"未找到 ID=$id 的图书,删除失败")
}
}
def calculateTotalAmount(books: scala.collection.mutable.ListBuffer[Book]): Double = {
books.map(book => book.price * book.amount).sum
}
}
}