src目录下的scala类
dao_bookDAO
package org.app
package daoimport models.BookModelimport scala.collection.mutable.ListBuffer//图书,数据操作
class BookDAO {//加载图书,从文件中读入def loadBooks(): ListBuffer[BookModel] = {val books = new ListBuffer[BookModel]()val source =scala.io.Source.fromFile("books.txt")for (line <- source.getLines()){val Array(id, name, author,available) = line.split(",")//books += BookModel(id.toInt, name, author, available.toBoolean)}//关闭连接source.close()books}//保存图书,将图书写入文件
def saveBooks(books:ListBuffer[BookModel]):Unit ={val writer = new java.io.PrintWriter(new java.io.File("books.txt"))for(book <- books){writer.println(book.id + "," + book.name + "," + book.author + "," + book.available)
}
writer.close()
}
}
dao_BorrowRecordDAO
package org.app
package daoimport org.app.models.BorrowRecordModelimport scala.collection.mutable.ListBuffer
import scala.io.Sourceclass BorrowRecordDAO{// 读出借阅记录def loadBorrowRecords(): ListBuffer[BorrowRecordModel] = {val borrowRecords = ListBuffer[BorrowRecordModel]()val lines = Source.fromFile("borrow_records.txt")for(line <- lines.getLines()){val parts = line.split(",")borrowRecords += BorrowRecordModel(parts(0),parts(1).toInt,parts(2),parts(3),if(parts.length>4)Some(parts(4))else None)// val Array(userName,bookID,bookName,borrowDate,returnDate) = line.split(",")// borrowRecords += BorrowRecordModel(userName,bookID.toInt,bookName,borrowDate,Some(returnDate))}borrowRecords}// 写入借阅记录def saveBorrowRecords(records: ListBuffer[BorrowRecordModel]): Unit = {val writer = new java.io.PrintWriter("borrow_records.txt")for(record <- records){writer.println(record.userName+","+record.bookID+","+record.bookName+","+record.borrowDate+","+record.returnDate.getOrElse(""))}writer.close()}
}
dao_UserDAO
package org.app
package daoimport models.{BookModel, UserModel}import scala.collection.mutable.ListBufferclass UserDAO {//加载所有的用户def loadUsers():ListBuffer[UserModel]={val users = new ListBuffer[UserModel]()val source = scala.io.Source.fromFile("users.txt")for (line <- source.getLines()) {val Array(username,password,role) = line.split(",")//users += UserModel(username,password,role)}//关闭连接source.close()users}//保存图书,将图书写入文件def saveUsers(users: ListBuffer[UserModel]): Unit = {val writer = new java.io.PrintWriter(new java.io.File("books.txt"))for (user <- users) {writer.println(user.username+ "," + user.password + "," + user.role)}writer.close()}
}
models_BookModel
package org.app
package models//图书类
//id,书名,作者,available:是否外借
case class BookModel(id:Int,name:String,author:String,var available:Boolean) {override def toString:String = {val availableStr = if(available) "可外借" else "已借出"s"编号:$id \t $name \t $author,$availableStr"}}
models_BorrowRecordModel
package org.app
package models//借阅记录类
case class BorrowRecordModel (userName: String, //借书人bookID:Int, //书籍IDbookName: String, //书籍名称borrowDate: String, //借书日期var returnDate: Option[String] = None //还书日期)
models_UserModel
package org.app
package modelscase class UserModel (username:String,password:String,role:String //普通用户){}
service_BookService
package org.app
package serviceimport org.app.dao.{BookDAO, BorrowRecordDAO}
import org.app.models.{BookModel, BorrowRecordModel}import java.time.LocalDateTime
import scala.collection.mutable.ListBuffer//图书业务逻辑层
class BookService {private val bookDAO = new BookDAO()private val borrowRecordDAO = new BorrowRecordDAO()//查询所有图书// def searchBooks(query: String): List[Book对象] = {def searchBooks(query: String): ListBuffer[BookModel] = {//从文本文件中读取书本信息,并保存列表中,返回val books = bookDAO.loadBooks()query match {case "" => bookscase _ => books.filter(b => b.name.contains(query) || b.author.contains(query)) //有条件,就过滤}}//普通用户,借阅图书def borrowBook(username: String, bookId: Int): Boolean = {//service//1,根据图书的·ID查询图书,判断图书书否存val books = bookDAO.loadBooks()val records = borrowRecordDAO.loadBorrowRecords()val book = books.find(b => b.id == bookId)if (book.nonEmpty) {val b = book.get//2.判断图书是否被借出if (b.available) {//3.借阅图书//更新这本书的状态b.available = false//把更新之后的图书信息写回txt文件中bookDAO.saveBooks(books)//TODO 添加一条借书的记录//读出当前全部记录//添加一条records += BorrowRecordModel(username, b.id, b.name, LocalDateTime.now().toString)//写回文件borrowRecordDAO.saveBorrowRecords(records)println("借阅成功")true} else {println("这本书被借走了")false}} else {false}}def queryBorrowRecords(username: String): ListBuffer[BorrowRecordModel] = {//1.把所有的记录全读出来val records = borrowRecordDAO.loadBorrowRecords()//2.过滤出当前用户借阅的记录records.filter(r => r.userName == username)}//普通用户,归还自己借得某一本书def returnBook(username: String, bookId: Int): Boolean = {//1.确定这本书是她本人借的还处于没有归还的状态queryBorrowRecords(username).find(r => r.bookID == bookId && r.returnDate.isEmpty) match {case Some(record) =>//2.更新书的状态//2.1 加载全部的书val books = bookDAO.loadBooks()//2.2选择当前这本书val b = books.find(_.id == bookId).getb.available = true//2.3把更新之后的状态写入到.txt文件中//3.更新借阅记录的状态//3.1加载全部的借阅记录val records = borrowRecordDAO.loadBorrowRecords()//3.2 找到当前这本书的借阅记录,bookID,useranme,returnDate = Noneval r = records.find(r => r.bookID == bookId && r.userName == username && r.returnDate.isEmpty).getr.returnDate = Some(LocalDateTime.now().toString)//3.3 把更新之后的状态写入到.txt文件中borrowRecordDAO.saveBorrowRecords(records)truecase None => false}}//添加图书def addBook(book: BookModel): Unit = {//1.生成一个book ID//查看所有的图书找到最大的ID +1var id = 1val books = bookDAO.loadBooks()if (books.nonEmpty){id = books.map(_.id).max + 1}//2.更新IDval newBook = book.copy(id = id)//3.把新的图书写入到.txt文件中books += newBook//4.写入到.txt文件中bookDAO.saveBooks(books)}
}
service_UserService
package org.app
package serviceimport dao.UserDAO
import org.app.models.UserModelclass UserService {private val userDAO = new UserDAO()//身份校验def authenticateUser(username:String,password:String):Option[UserModel]={//根据用户名和密码查询,是否符合要求val users = userDAO.loadUsers()users.find(user=>user.username==username && user.password == password)}def addUsre(username: String): Boolean = {//1.查询用户名是否已经存在val users = userDAO.loadUsers()val user = users.find(_.username == username)if(user.isEmpty){//2.如果不存在,则添加//2.1 读出所有的用户//2.2 创建新的用户.设置用户密码,123,类别,普通用户users += UserModel(username,"123","普通用户")//2.3 将用户添加文件合中userDAO.saveUsers(users)true}else{false}}
}
UI_library
package org.app
package uiimport org.app.models.{BookModel, UserModel}
import org.app.service.{BookService, UserService}import scala.io.StdIn
import scala.io.StdIn.readLineclass library {private val BookService = new BookService()private val UserService = new UserService()//调用方法,输入图书的信息,返回BookModelprivate def inputBookInfo(): BookModel = {println("请输入图书名称:")val name = readLine().trimprintln("请输入图书作者:")val author = readLine().trimprintln("请输入图书是否借出:(ture/false):")val available = StdIn.readBoolean()//初始设置编号为0BookModel(0,name, author, available)}// 显示游客的菜单def showVisitorMenu(): Unit = {var running = truewhile (running) {println("欢迎来到我的图书管理系统, 请选择")println("1. 查看所有图书")println("2. 查询图书")println("3. 登录")println("4. 离开")// 获取用户的操作val choice = StdIn.readLine().trimchoice match {case "1" =>// 调用业务逻辑层的方法val results = BookService.searchBooks("")if(results.nonEmpty){results.foreach(println)} else {println("没有找到图书")}case "2" =>// 提示用户输入查询关键字val query = readLine("请输入查询关键字(书名,作者):").trim// 根据关键字去查询图书列表,找到满足条件的书val results = BookService.searchBooks(query)// 显示出来if(results.nonEmpty){println("=======查询图书的结果:=======")results.foreach(println)} else {println("没有找到图书")}case "3" =>println("请输入用户名:")val username = StdIn.readLine().trimprintln("请输入密码:")val password = StdIn.readLine().trim// 调用Service的方法,进行登录val userOpt = UserService.authenticateUser(username, password)if(userOpt.isEmpty){println("用户名或密码错误")} else {println("登录成功")// 登录成功,显示登录用户的菜单val user = userOpt.getuser.role match {case "管理员" => showAdminMenu(user)case "普通用户" => showUserMenu(user)}}case "4" =>running = falseprintln("感谢你的使用,下次再见")case _ => println("无效的选择")}}}// 显示管理员的菜单def showAdminMenu(user:UserModel): Unit = {var running = truewhile (running) {println(s"欢迎管理员:${user.username},来到我的图书管理系统, 请选择")println("1. 添加图书")println("2. 查询图书")println("3. 添加用户")println("4. 退出")// 获取用户的操作val choice = StdIn.readLine().trimchoice match {case "1" =>//1.获取图书信息,书名,作者,状态val book = inputBookInfo()println(book)//2. 调用Service的方法,进行图书的添加books.txt文件中BookService.addBook(book)println(s"图书:${book.name}添加成功 ")case "2" => println("查询图书")case "3" =>//1.获取用户信息,用户名val username = StdIn.readLine("请输入用户名: ")if(UserService.addUsre(username)){println(s"用户:${username}添加成功 ")}else{println(s"用户:${username}添加失败 ")}//2. 调用Service的方法,进行用户的添加users.txt文件中case "4" => running = falsecase _ => println("无效的选择")}}}// 显示登录用户的菜单def showUserMenu(user:UserModel): Unit = {var running = truewhile (running) {println(s"欢迎用户:${user.username},来到我的图书管理系统, 请选择")println("1. 借阅图书")println("2. 查询借阅图书")println("3. 还书图书")println("4. 退出")// 获取用户的操作val choice = StdIn.readLine().trimchoice match {case "1" =>// UI: 提示用户输入图书的ID。校验:判断是不是整数try {val id = readLine("请输入图书的ID:").toIntBookService.borrowBook(user.username, id)} catch {case e:Exception =>println(e)println("输入的图书ID无效")}case "2" =>println("查询借阅图书")// 在BookService中实现根据用户名去查询借阅图书val borrowRecords = BookService.queryBorrowRecords(user.username)//判断是否为空if(borrowRecords.isEmpty){println("没有借阅记录")}else{//遍历借阅记录for(record <- borrowRecords){println(record)val returnDate = record.returnDate.getOrElse("未归还")println(s"书名:${record.bookName} 借阅日期:${record.borrowDate} 归还日期:${returnDate}")}}case "3" =>try {val id = readLine("请输入要还书图书的ID:").toIntif(BookService.returnBook(user.username, id)){println("归还图书成功")}else{println("归还图书失败")}} catch {case e: Exception =>println(e)println("输入的图书ID无效")}case "4" => running = falsecase _ => println("无效的选择")}}}def showMenu(): Unit = {showVisitorMenu()}
}
Main方法
package org.appimport org.app.ui.libraryobject Main {def main(args: Array[String]): Unit = {val m = new library()m.showMenu()}}
books.txt文件
1,人性的弱点,卡耐基,false 2,理想国,柏拉图,true 3,埃隆・马斯克传,艾萨克森,true 4,苏东坡传,林语堂,true 5,杨苡口述自传,杨苡、余斌,true 6,曾国藩传,张宏杰,true 7,知行合一王阳明,度阴山,true 8,暮色将尽,戴安娜・阿西尔,true 9,你当像鸟飞往你的山,塔拉・韦斯特弗,true 10,邓小平时代,傅高义,true
borrow_records.txt文件
借书还书会自动更新记录
users.txt文件
fan,123,普通用户 adimin,123,管理员