要编写这个程序我们首相要清楚这个程序中有哪些对象,不考虑复杂情况,基本的对象有三个:
那么我们就分别讨论这三个对象有哪些属性和有哪些动作。
我们把这三个对象分别放入三个包中,这样在分别完成这些对象中所需的动作(方法)。
我们书籍包中的代码:
package book;
public class Book {
private String name;
private String id;
private String author;
private String type;
private int price;
private boolean isBorrow;
public Book(String name, String id, String author, String type, int price, boolean isBorrow) {
this.name = name;
this.id = id;
this.author = author;
this.type = type;
this.price = price;
this.isBorrow = isBorrow;
}
public String getId() {
return id;
}
public boolean isBorrow() {
return isBorrow;
}
public void setBorrow(boolean borrow) {
isBorrow = borrow;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", id='" + id + '\'' +
", author='" + author + '\'' +
", type='" + type + '\'' +
", price=" + price +
", isBorrow=" + isBorrow +
'}';
}
}
同时创建一个类似顺序表的书籍数组保存书籍。
package book;
public class BookList {
private Book[] books = new Book[100];
private int size;
public BookList() {
books[0] = new Book("金瓶梅",
"001", "兰陵笑笑生","古典名著",
100, false);
books[1] = new Book("水浒传",
"002", "施耐庵","古典名著",
100, false);
books[2] = new Book("西游记",
"003", "吴承恩","古典名著",
100, false);
size = 3;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public Book getBook(int index) {
return books[index];
}
public void setBooks(int index, Book book) {
books[index] = book;
}
}
我们将用所有的操作方法放入operation包中,所有的方法都用接口来实现,这样我们就避免了使用一大堆的 if else
接口:
package operation;
import book.BookList;
public interface IOperation {
void work(BookList bookList);
}
增加新书籍:
package operation;
import book.Book;
import book.BookList;
import java.util.Scanner;
public class AddBookOperation implements IOperation{
@Override
public void work(BookList bookList) {
System.out.println("新增一本书籍!");
System.out.println("请输入新增书籍的书名: ");
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
System.out.println("请输入新增书籍的id: ");
String id = scanner.next();
System.out.println("请输入新增书籍的作者: ");
String author = scanner.next();
System.out.println("请输入新增书籍的类型: ");
String type = scanner.next();
System.out.println("请输入新增书籍的价格: ");
int price = scanner.nextInt();
Book book = new Book(name, id, author, type, price, false);
bookList.setBooks(bookList.getSize(), book);
bookList.setSize(bookList.getSize() + 1);
}
}
删除书籍:
package operation;
import book.Book;
import book.BookList;
import java.util.Scanner;
public class DeleteBookOperation implements IOperation {
@Override
public void work(BookList bookList) {
System.out.println("删除书籍!");
System.out.println("请输入您想要删除书籍的id: ");
Scanner scanner = new Scanner(System.in);
String id = scanner.next();
int i = 0;
for (; i < bookList.getSize(); i++) {
Book book = bookList.getBook(i);
if (book.getId().equals(id)) {
break;
}
}
if (i >= bookList.getSize()) {
System.out.println("未找到要找的书籍!");
return;
}
Book lastBook = bookList.getBook(bookList.getSize() - 1);
bookList.setBooks(i, lastBook);
bookList.setSize(bookList.getSize() - 1);
System.out.println("删除成功!");
}
}
查找书籍:
package operation;
import book.Book;
import book.BookList;
import java.util.Scanner;
public class FindOperation implements IOperation {
@Override
public void work(BookList bookList) {
System.out.println("查找书籍!");
System.out.println("请输入要查找书籍的书名: ");
Scanner scanner = new Scanner(System.in);
String name = scanner.next();
int count = 0;
for (int i = 0; i < bookList.getSize(); i++) {
Book book = bookList.getBook(i);
if (book.getName().equals(name)) {
System.out.println(book);
count++;
}
}
if (count == 0) {
System.out.println("没找到此书籍!");
} else {
System.out.println("共找到 " + count + " 本相同书籍!");
}
}
}
借阅书籍:
package operation;
import book.Book;
import book.BookList;
import java.util.Scanner;
public class BorrowOperation implements IOperation {
@Override
public void work(BookList bookList) {
System.out.println("借阅书籍!");
System.out.println("请输入要借阅的书籍的id: ");
Scanner scanner = new Scanner(System.in);
String id = scanner.next();
for (int i = 0; i < bookList.getSize(); i++) {
Book book = bookList.getBook(i);
if (!book.getId().equals(id)) {
continue;
}
if (book.isBorrow()) {
System.out.println("此书已经被借走了!");
break;
}
book.setBorrow(true);
System.out.println("借阅成功");
}
}
}
归还书籍:
package operation;
import book.Book;
import book.BookList;
import java.util.Scanner;
public class ReturnOperation implements IOperation {
@Override
public void work(BookList bookList) {
System.out.println("归还书籍!");
System.out.println("请输入要归还书籍的id: ");
Scanner scanner = new Scanner(System.in);
String id = scanner.next();
int i = 0;
for ( ; i < bookList.getSize(); i++) {
Book book = bookList.getBook(i);
if (!book.getId().equals(id)) {
continue;
}
if (!book.isBorrow()) {
System.out.println("这本书未借出去,归还失败!");
}
book.setBorrow(false);
}
}
}
打印所有书籍信息:
package operation;
import book.BookList;
public class PrintAllOperation implements IOperation {
@Override
public void work(BookList bookList) {
for (int i = 0; i < bookList.getSize(); i++) {
System.out.println(bookList.getBook(i));
}
System.out.println("共有 " + bookList.getSize() + " 本书籍");
}
}
退出系统:
package operation;
import book.BookList;
public class ExitOperation implements IOperation {
@Override
public void work(BookList bookList) {
System.out.println("GoodBye!");
System.exit(0);
}
}
我们用户中先创建一个抽象的用户,再将不同用户通过实现这个抽象的用户来实现不同用户的操作权限。
我们用户包中的代码
抽象的用户代码:
package user;
import book.BookList;
import operation.IOperation;
abstract public class User {
protected String name;
protected IOperation[] operations;
public User(String name) {
this.name = name;
}
abstract public int menu();
public void doOperation(int choice, BookList bookList) {
operations[choice].work(bookList);
}
}
管理员用户:
package user;
import book.BookList;
import operation.*;
import java.util.Scanner;
public class Admin extends User{
public Admin(String name) {
super(name);
operations = new IOperation[] {
new ExitOperation(),
new AddBookOperation(),
new DeleteBookOperation(),
new FindOperation(),
new PrintAllOperation(),
};
}
@Override
public int menu() {
System.out.println("============");
System.out.println("hello " + name);
System.out.println("1. 增加书籍");
System.out.println("2. 删除书籍");
System.out.println("3. 查找书籍");
System.out.println("4. 打印所有信息");
System.out.println("0. 退出");
System.out.println("============");
System.out.println("请输入您的选择: ");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
return choice;
}
}
普通用户:
package user;
import operation.*;
import java.util.Scanner;
public class NormalUser extends User {
public NormalUser(String name) {
super(name);
operations = new IOperation[] {
new ExitOperation(),
new FindOperation(),
new BorrowOperation(),
new ReturnOperation(),
};
}
@Override
public int menu() {
System.out.println("============");
System.out.println("hello " + name);
System.out.println("1. 查找图书");
System.out.println("2. 借阅图书");
System.out.println("3. 归还图书");
System.out.println("0. 退出");
System.out.println("============");
System.out.println("请输入您的选择: ");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
return choice;
}
}
这样就完成了一个简单的图书馆管理系统。
这是测试类代码块
import book.BookList;
import user.Admin;
import user.NormalUser;
import user.User;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
BookList bookList = new BookList();
User user = login();
while (true) {
int choice = user.menu();
user.doOperation(choice, bookList);
}
}
public static User login() {
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎来到图书管理系统!");
System.out.println("请输入您的姓名: ");
String name = scanner.next();
System.out.println("请输入您的用户选项: 1 -> 管理员 2 -> 普通用户");
int role = scanner.nextInt();
if (role == 1) {
return new Admin(name);
} else {
return new NormalUser(name);
}
}
}
新增登录、注册模块
创建dao包
我们的用户User类,包含用户名, 密码
package dao;
public class User {
String username;
String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserDao包含登录和注册
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UserDao {
//注册
public void login(User user) {
Connection connection = DBUtil.getConnection();
PreparedStatement statement = null;
String sql = "insert into user values(?, ?)";
try {
statement = connection.prepareStatement(sql);
statement.setString(1, user.getUsername());
statement.setString(2, user.getPassword());
int ret = statement.executeUpdate();
if (ret != 1) {
System.out.println("当前数据库执行插入数据出错");
return;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
DBUtil.close(connection, statement, null);
}
}
//登录
public int enter(String username, String password) {
List<String> list = new ArrayList<>();
Connection connection = DBUtil.getConnection();
String sql = "select username, password from user where username = ?";
PreparedStatement statement = null;
ResultSet resultSet = null;
int ret = 0;
try {
statement = connection.prepareStatement(sql);
statement.setString(1, username);
while (resultSet.next()) {
String pass = resultSet.getString(password);
list.add(pass);
}
if (list.contains(password)) {
ret = 1;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
DBUtil.close(connection, statement, resultSet);
}
return ret;
}
}
DBUtil实现连接数据库
package dao;
import java.sql.*;
public class DBUtil {
private static final String URL = "jdbc:mysql://localhost:3306/java_github_crawler";
private static final String USERNAME = "root";
private static final String PASSWORD = "123456";
private static Connection conn = null;
static{
try {
//1.加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
//2. 获得数据库连接
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
return conn;
}
//释放资源
public static void close(Connection connection, Statement statement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (Exception e) {
throw new RuntimeException("释放数据库资源失败", e);
}
}
}
新的测试类:
import book.BookList;
import dao.UserDao;
import user.Admin;
import user.NormalUser;
import user.User;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
BookList bookList = new BookList();
User user = login();
if (user == null) {
return;
}
while (true) {
int choice = user.menu();
user.doOperation(choice, bookList);
}
}
public static User login() {
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎来到图书管理系统!");
dao.User user = new dao.User();
System.out.println("请输入您的用户选项: 1 -> 注册 2 -> 登录");
int role = scanner.nextInt();
UserDao userDao = new UserDao();
boolean isEnter = false;
if (role == 1) {
System.out.println("请输入用户名: ");
user.setUsername(scanner.nextLine());
System.out.println("请输入密码: ");
user.setPassword(scanner.nextLine());
userDao.login(user);
} else {
for (int i = 3; i >= 0; i--) {
System.out.println("请输入用户名: ");
String username = scanner.nextLine();
System.out.println("请输入密码: ");
String password = scanner.nextLine();
int ret = userDao.enter(username, password);
if (ret != 1) {
System.out.println("登录失败,您还有 " + i + "次机会");
} else {
System.out.println("登录成功");
isEnter = true;
break;
}
}
}
if (!isEnter) {
return null;
}
String name = user.getUsername();
System.out.println("请输入您的用户选项: 1 -> 管理员 2 -> 普通用户");
if (role == 1) {
return new Admin(name);
} else {
return new NormalUser(name);
}
}
}