自学内容网 自学内容网

Scala的List习题

答案:BABCB

import java.awt.print.Book
import scala.collection.mutable.ListBuffer
//1
class Book(var bookName:String,var bookAuthor:String,var price:Double){

}


object p3 {
  def main(args: Array[String]): Unit = {
    val bookList = ListBuffer[Book]()
    //2
    bookList += new Book("书1","作者1",33)
    bookList += new Book("书2","作者2",22)
    bookList += new Book("书3","作者3",56)
    bookList += new Book("书4","作者4",76)
    bookList += new Book("书5","作者5",45)
    bookList += new Book("书6","作者6",78)
    println(bookList)

    //3
    bookList.prepend(new Book("书7","作者7",44.9))
    println(bookList)

    //4
    bookList.insert(2,new Book("书8","作者8",29.53))
    println(bookList)

    //5
    def bookExists(bookName: String, bookList: ListBuffer[Book]): Boolean = {
      for (book <- bookList) {
        if (book.bookName == bookName) {
          return true
        }
      }
      false
    }
    val exists = bookExists("书8", bookList)
    println(exists)


    //6
    bookList.remove(3)

    //7
    val sortedBooks = bookList.toList.sortBy(-_.price)

    //8
    sortedBooks.foreach(
      book => println(s"Title: ${book.bookName},Author: ${book.bookAuthor}, Price: ${book.price}"))


  }
}


原文地址:https://blog.csdn.net/2403_87107889/article/details/143584923

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!