Scala项目(一)
1,创建dao,models,service,ui等软件包
2,在各软件包下创建scala类
软件包dao里的代码
package org.app
package dao
import models.BookModel
import 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
}
}
软件包models里的代码
package org.app
package models
//图书类
//id,书名,作者,available:是否外借
case class BookModel(id:Int,name:String,author:String,available:Boolean) {
}
软件包service代码
package org.app
package service
import org.app.dao.BookDAO
import org.app.models.BookModel
import scala.collection.mutable.ListBuffer
//图书业务逻辑层
class BookService {
private val bookDAO = new BookDAO()
//查询所有图书
// def searchBooks(query: String): List[Book对象] = {
def searchBooks(query: String): ListBuffer[BookModel] = {
//从文本文件中读取书本信息,并保存列表中,返回
bookDAO.loadBooks()
}
}
ui软件包里的代码
package org.app
package UI
import org.app.service.BookService
import scala.io.StdIn
class Library {
private val BookService = new BookService()
def showMenu(): Unit = {
showVisitorMenu()
}
def showVisitorMenu(): Unit = {
var running = true
while (running) {
println("欢迎来到我的图书馆系统,请选择")
println("1.查看所有图书")
println("2.查询图书")
println("3.登录")
println("4.离开")
//获取用户的操作
val choice = StdIn.readLine().trim
choice match {
case "1" =>
println("查看所有图书")
//TODO 查看所有图书
val results = BookService.searchBooks("")
if (results.nonEmpty){
results.foreach(println)
}else{
println("没有找到图书")
}
case "2" => println("查询图书")
case "3" => println("登录")
case "4" =>
running = false
println("感谢你的使用,下次再见")
case _ => println("无效的选择")
}
}
}
}
src目录下的代码
package org.app
import org.app.UI.Library
import scala.io.StdIn
object Main {
def main(args: Array[String]): Unit = {
val m = new Library()
m.showMenu()
}
}
在项目下新建文件books.txt复制一些书籍作者,书籍名称,是否外借。
最后在软件包ui里的scala中调用代码。