使用case class 创建图书馆信息

22 阅读1分钟

1.使用case class 创建图书馆信息类Book:包含四个属性:ID,书名,作者,价格,数量

2.创建一个名为bookList的可变List,它只能用来保存Book的实例

3.初始化三本不同的书(注意id不同就是不同的书)。加入到bookList中

4.添加一本已经存在的书。此时应该去修改bookList中对应书目的数量,而不是去添加一条新数据

5.根据图书名称查询是否在列表中(通过遍历列表对比名称 ) 6.删除指定书名的书

7.删除指定ID的书

8.对于图书馆按价格从高到低排序

9.遍历图书列表,并打印每本书的详情信息

10.计算全部总的金额

eg:``` package caseclass

import scala.collection.mutable.ListBuffer

case class Book(id: String, title: String, author: String, price: Double, quantity: Int)

object caseclass02 { def main(args: Array[String]): Unit = { // 创建可变List保存Book实例 val bookList = ListBufferBook

// 初始化三本不同的书
bookList += Book("001", "Scala编程", "Martin Odersky", 89.0, 3)
bookList += Book("002", "Java核心技术", "Cay Horstmann", 128.0, 2)
bookList += Book("003", "Python编程", "Guido van Rossum", 75.0, 5)

// 打印初始列表
println("初始图书列表:")
printAllBooks(bookList)

// 添加已存在的书(更新数量)
println("\n添加已存在的书:")
addBook(bookList, Book("001", "Scala编程", "Martin Odersky", 89.0, 2))
printAllBooks(bookList)

// 查询图书
println(s"\n查找'Scala编程': ${findBookByName(bookList, "Scala编程")}")

// 按价格排序
println("\n按价格从高到低排序:")
sortBooksByPrice(bookList)
printAllBooks(bookList)

// 计算总金额
println(s"\n图书总价值: ${calculateTotalAmount(bookList)}")

}

def addBook(bookList: ListBuffer[Book], book: Book): Unit = { val index = bookList.indexWhere(_.id == book.id) if (index >= 0) { val existingBook = bookList(index) val updatedBook = existingBook.copy(quantity = existingBook.quantity + book.quantity) bookList.update(index, updatedBook) } else { bookList += book } }

def findBookByName(bookList: ListBuffer[Book], title: String): Boolean = { bookList.exists(_.title == title) }

def removeBookByName(bookList: ListBuffer[Book], title: String): Unit = { val index = bookList.indexWhere(_.title == title) if (index >= 0) { bookList.remove(index) } }

def removeBookById(bookList: ListBuffer[Book], id: String): Unit = { val index = bookList.indexWhere(_.id == id) if (index >= 0) { bookList.remove(index) } }

def sortBooksByPrice(bookList: ListBuffer[Book]): Unit = { val sortedList = bookList.sortBy(-_.price) bookList.clear() bookList ++= sortedList }

def printAllBooks(bookList: ListBuffer[Book]): Unit = { bookList.foreach(book => println(s"ID: book.id,书名:{book.id}, 书名: {book.title}, 作者: book.author,价格:{book.author}, 价格: {book.price}, 数量: ${book.quantity}") ) }

def calculateTotalAmount(bookList: ListBuffer[Book]): Double = { bookList.map(book => book.price * book.quantity).sum } }