scala借阅图书保存记录(三)

server/2024/12/26 10:05:56/

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]):Unilt ={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()
}
}
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()}
}
package org.app
package daoimport models.UserModelimport scala.collection.mutable.ListBufferclass UserDAO {//加载所有的用户def loadUsers():List[UserModel]={val books = new ListBuffer[UserModel]()val source = scala.io.Source.fromFile("books.txt")for (line <- source.getLines()) {val Array(username,password,role) = line.split(",")//books += UserModel(username,password,role)}//关闭连接source.close()users}
}

BookModel

package org.app
package models//图书类
//id,书名,作者,available:是否外借
case class BookModel(id:Int,name:String,author:String,available:Boolean) {override def toString:String = {val availableStr = if(available) "可外借" else "已借出"s"编号:$id \t $name \t $author,$availableStr"}}
BorrowRecordModel
package org.app
package models//借阅记录类
case class BorrowRecordModel (userName: String,   //借书人bookID:Int,          //书籍IDbookName: String,      //书籍名称borrowDate: String,      //借书日期returnDate: Option[String] = None       //还书日期)

UsreModel

package org.app
package modelscase class UserModel (username:String,password:String,role:String //普通用户){}

BookService

package org.app
package serviceimport org.app.dao.{BookDAO, BorrowRecordDAO}
import org.app.models.{BookModel, BorrowRecordModel}import java.time.{LocalDate, 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(book.get.available){val b = book.get
//3.借阅图书
//更新这本书的状态
val 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}
}
}

UserService

package org.app
package serviceimport dao.UserDAOimport 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)}}

library

package org.app
package uiimport org.app.models.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()// 显示游客的菜单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("4. 退出")// 获取用户的操作val choice = StdIn.readLine().trimchoice match {case "1" => println("添加图书")case "2" => println("查询图书")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 "4" => running = falsecase _ => println("无效的选择")}}}def showMenu(): Unit = {showVisitorMenu()}
}


http://www.ppmy.cn/server/152987.html

相关文章

SQL 实战:窗口函数的妙用 – 分析排名与分组聚合

在复杂的数据分析和查询场景中&#xff0c;SQL 窗口函数&#xff08;Window Functions&#xff09;是提升性能和代码可读性的重要工具。窗口函数可以轻松实现排名、分组聚合、滑动平均等复杂计算&#xff0c;避免使用嵌套子查询或冗余的多次表扫描。 本文将通过实战案例&#…

电子应用设计方案71:智能客厅窗帘系统设计

智能客厅窗帘系统设计 一、引言 智能客厅窗帘系统为用户提供了更加便捷、舒适和个性化的窗帘控制方式&#xff0c;提升了家居的智能化水平和生活品质。 二、系统概述 1. 系统目标 - 实现客厅窗帘的自动开合控制&#xff0c;可通过多种方式操作。 - 能够根据时间、光照强度和用…

容器技术所涉及Linux内核关键技术

容器技术所涉及Linux内核关键技术 一、容器技术前世今生 1.1 1979年 — chroot 容器技术的概念可以追溯到1979年的UNIX chroot。它是一套“UNIX操作系统”系统&#xff0c;旨在将其root目录及其它子目录变更至文件系统内的新位置&#xff0c;且只接受特定进程的访问。这项功…

树莓派换源

查询自己版本&#xff1a; lsb_release -a bullseye可以理解为树莓派的系统代号&#xff08;10&#xff0c;11&#xff0c;12都不同&#xff0c;一定要看好自己系统是什么版本&#xff09; 查询架构 uname -a aarch64的地方就是代表系统架构的&#xff0c;我的是aarch64的架…

安装指南|OpenCSG Starship上架GitHub Marketplace

在代码开发的日常中&#xff0c;你是否常常被以下问题困扰&#xff1f; 代码审查耗时太长&#xff0c;拖慢项目进度&#xff1f; 审查质量参差不齐&#xff0c;一些关键问题被遗漏&#xff1f; 复杂代码变更看不懂&#xff0c;审查者需要大量时间理解意图&#xff1f; 别担…

apache应用(客户机地址限制、用户授权限制、日志分割、AWStats日志分析)

目录 一、 客户机地址限制 二、 用户授权限制 三、 日志分割 使用rotatelogs分割工具 使用第三方工具cronolog 四、 AWStats日志分析 具体的apache软件安装可以阅读我之前的文章apache安装https://blog.csdn.net/m0_68472908/article/details/139348739?spm1001.2014.300…

C调用gnuplot绘图的方法

每次调试都先从C中抓数据&#xff0c;然后再拷贝到py或者matlab中绘图&#xff0c;太麻烦&#xff0c;为了提高效率&#xff0c;可以考虑C调用gnuplot的方案&#xff08;当然C调用py的matplotlib应该也是可以的&#xff09; 废话不多说&#xff0c;直接上代码&#xff1a; #i…

深度学习中的特征到底是什么?

深度学习中的特征到底是什么&#xff1f; 深度学习中的特征到底是什么&#xff1f; 特征要有对比才能更好地认识和区别。 常见的图像特征,如sobel边缘算子,提取出来的是图像的边缘特征信息,表示的是图像中像素有突 变的地方,然后用一个3*3的滤波器模板去提取出来。又比如LBP…