import scala.collection.mutable.ListBuffer
class Book(var name:String,var author:String,var price:Double){
}
object Test20_1 {
def main(args: Array[String]): Unit = {
var bookList = ListBuffer[Book]()
// 创建六本图书对象并添加到列表尾部
bookList += new Book("Book1", "Author1", 20.0)
bookList += new Book("Book2", "Author2", 25.0)
bookList += new Book("Book3", "Author3", 18.0)
bookList += new Book("Book4", "Author4", 30.0)
bookList += new Book("Book5", "Author5", 22.0)
bookList += new Book("Book6", "Author6", 15.0)
// 创建一本图书对象并添加到列表头部
bookList.prepend(new Book("NewBook1", "NewAuthor1", 28.0))
// 创建一本图书对象并添加到列表第三个位置
bookList.insert(2, new Book("NewBook2", "NewAuthor2", 32.0))
// 根据图书名称查询是否在列表中
def isBookInList(name: String): Boolean = {
for (book <- bookList) {
if (book.name == name) return true
}
false
}
val bookNameToSearch = "Book3"
println(s"Is $bookNameToSearch in the list? ${isBookInList(bookNameToSearch)}")
// 从列表中删除第四本书
bookList.remove(3)
// 图书价格按从高到低排序
val sortedList = bookList.sortBy(-_.price)
// 遍历图书列表并打印每本书的详细信息
println("Book List Details:")
for (book <- sortedList) {
println(s"Name: ${book.name}, Author: ${book.author}, Price: ${book.price}")
}
// 展示全部的总的金额
val totalAmount = sortedList.map(_.price).sum
println(s"Total amount: $totalAmount")
}
}