[Java] phased summary exercise -- implementation of library management system

Posted by neogranas on Mon, 10 Jan 2022 14:42:10 +0100

After learning the knowledge of object-oriented programming syntax and simple data structure sequence table, we can now use these knowledge to comprehensively implement a library management system to test the mastery of the previous knowledge and practice the actual coding ability of the code, so as to further understand Java development. We don't say much and begin to explain~

1. Implementation of book package

First, we implement a book package, in which a Book class is defined respectively to realize the definition and operation of books; And a BookList class, equivalent to a bookshelf, used to store books. In essence, it is a sequential table in a data structure to find and modify specific books.

//Relevant explanations are given in the form of comments in the code. Please pay attention to them

1.1 Book class

package book;

public class Book {
    private String name; //title
    private String author;//author
    private int price;//book prices
    private String type;//Types of books
    private boolean isBorrowed;//Is the status of the book lent

//Rewrite construction method is used to define a book
    public Book(String name, String author, int price, String type) {
        this.name = name;
        this.author = author;
        this.price = price;
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public boolean isBorrowed() {
        return isBorrowed;
    }

    public void setBorrowed(boolean borrowed) {
        isBorrowed = borrowed;
    }

//Override the toString method to print the book information
    @Override 
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                ", type='" + type + '\'' + " "+
                ((isBorrowed==true)?"Has been lent out":"Not lent")+
                '}';
    }
}

1.2 BookList class

package book;

public class BookList {
    private Book[] books=new Book[10]; //Define an array of Book type and initialize the space for 10 books
    private int usedSize;//Number of books currently in storage
    public BookList(){
        books[0]=new Book("Romance of the Three Kingdoms","Luo Guanzhong",17,"novel");
        books[1]=new Book("Journey to the West","Wu Chengen",47,"novel");
        books[2]=new Book("Water Margin","Shi Naian",37,"novel"); //Give three books for practice
        this.usedSize=3;
    }

    public int getUsedSize() {
        return usedSize;
    }

    public void setUsedSize(int usedSize) {
        this.usedSize = usedSize;
    }

    /**
     * Get a book at pos
     * @param pos
     * @return
     */
    public Book getPos(int pos){
        return this.books[pos];
    }

    /**
     * Set the subscript of pos position as a Book (add a Book)
     * @param pos
     * @param book
     */
    public void setBook(int pos,Book book){
        this.books[pos]=book;
    }

}

2.operation package

Because object-oriented programming practice is required, an operation package is implemented separately to realize various operations on books. The original code of this part can be placed in the sequence table of BookList, but the operation package can have a clearer understanding of object-oriented programming~

2.1 IOperation interface

package operation;

import book.BookList;

import java.util.Scanner;

public interface IOperation {
    void work(BookList bookList);
    //The keyboard input data code can be directly implemented in the interface without writing the necessary code in each class
    Scanner scanner=new Scanner(System.in);

}

2.2 AddOperation class

This class implements the function of adding books

package operation;

import book.Book;
import book.BookList;

import java.util.Scanner;

public class AddOperation implements IOperation { //Implementation interface
    public void work(BookList bookList) { //Method of rewriting interface
        System.out.println("New books!");
        System.out.println("Please enter the name of the book to be added:");
        String name = scanner.nextLine();
        System.out.println("Author:");
        String author = scanner.nextLine();
        System.out.println("Type:");
        String type = scanner.nextLine();
        System.out.println("Price:");
        int price = scanner.nextInt();

        Book book = new Book(name, author, price, type);//Construct a book that needs to be added
        int size = bookList.getUsedSize();
        bookList.setBook(size, book);
        bookList.setUsedSize(size + 1);
        System.out.println("Successfully added books!");

    }
}

2.2 BorrowOperation class

Book borrowing function

package operation;

import book.Book;
import book.BookList;

public class BorrowOperation implements IOperation{
    public void work(BookList bookList){
        System.out.println("Borrow books!");
        System.out.println("Please enter the name of the book you want to borrow:");
        String name=scanner.nextLine();
        int size=bookList.getUsedSize();
        for (int i = 0; i < size; i++) {
            Book book=bookList.getPos(i);
            if (name.equals(book.getName())){
                book.setBorrowed(true);
                System.out.println("Borrowing succeeded!");
                System.out.println(book);
                return;
            }
        }
        System.out.println("I can't find the book you want to borrow!");
    }
}

2.3 ReturnOperation class

Return book function

package operation;

import book.Book;
import book.BookList;

public class ReturnOperation implements IOperation{
    public void work(BookList bookList){
        System.out.println("Return the books!");
        System.out.println("Please enter the name of the book you want to return:");
        String name=scanner.nextLine();
        int size=bookList.getUsedSize();
        for (int i = 0; i < size; i++) {
            Book book=bookList.getPos(i);
            if (name.equals(book.getName())){
                book.setBorrowed(false);
                System.out.println("Return succeeded!");
                System.out.println(book);
                return;
            }
        }
        System.out.println("I haven't found the book you want to return!");
    }
}

2.4 DelOperation class

Delete specified book function

package operation;

import book.Book;
import book.BookList;

public class DelOperation implements IOperation{
    public void work(BookList bookList){
        System.out.println("Delete books!");
        //1. Find the location of the book according to the book title
        System.out.println("Please enter the title of the book you want to delete:");
        String name=scanner.nextLine();
        int currentSize=bookList.getUsedSize();
        int index=0; //Store the subscript of the book to be deleted
        int i = 0;
        for (; i < currentSize; i++) {
            Book book=bookList.getPos(i);
            if (book.getName().equals(name)){
                index=i;
                break;
            }
        }
        if (i>=currentSize){
            System.out.println("There is no book you want to delete!");
            return;
        }
        //2. Delete!
        for (int j = index; j < currentSize-1; j++) { //The reason why it is less than currentSize-1 is to avoid the array out of bounds and error reporting. The deletion operation only needs to find the currentSize-1 subscript
            Book book=bookList.getPos(j+1);
            bookList.setBook(j,book); //The operation idea is to give the j+1 subscript content to j to realize the deletion effect
        }
        bookList.setBook(currentSize,null); //Don't forget to empty the last subscript
        bookList.setUsedSize(currentSize-1);//The number of books is reduced by one
        System.out.println("Delete succeeded!");
    }
}

2.5 DisplayOperation class

Print the current bookshelf information

package operation;

import book.Book;
import book.BookList;

public class DisplayOperation implements IOperation{
    public void work(BookList bookList){
        System.out.println("Print books!");
        int size=bookList.getUsedSize();
        for (int i = 0; i < size; i++) {
            Book book=bookList.getPos(i);
            System.out.println(book);
        }
    }
}

2.6 FindOperation class

Realize the function of finding specified books and printing book information

package operation;

import book.Book;
import book.BookList;

public class FindOperation implements IOperation{
    public void work(BookList bookList){
        System.out.println("Find books!");
        String name=scanner.nextLine();
        int size=bookList.getUsedSize();
        for (int i = 0; i < size; i++) {
            Book book=bookList.getPos(i);
            if (name.equals(book.getName())){
                System.out.println("Found the book,The information is as follows:");
                System.out.println(book);
                return;
            }
        }
        System.out.println("I didn't find the book!");
    }
}

2.7 ExitOperation class

Realize the function of exiting the library management system

package operation;

import book.BookList;

public class ExitOperation implements IOperation{
    public void work(BookList bookList){
        System.out.println("Exit the system!");
        System.exit(0); //0 indicates normal exit
    }
}

3.user package

Because different functions need to be implemented for different users, the user package here implements the functions required by administrators and ordinary users respectively

3.1 User class (parent class)

package user;

import book.BookList;
import operation.IOperation;

public abstract class User { //Abstract class implementation
    protected String name; //User name
    protected IOperation[] iOperations;//Interface array implementation
    public User(String name){ //Override User constructor
        this.name=name;
    }
    public abstract  int menu(); //Different user menus are implemented for different user input options

//Select and implement different operation operations according to user input
    public void doWork(int choice, BookList bookList){
        iOperations[choice].work(bookList);
    }
}

3.2 AdminUser administrator class (subclass)

package user;

import operation.*;

import java.util.Scanner;

public class AdminUser extends User{
    public AdminUser(String name){ //Subclass construction method
        super(name); //Override parent class constructor
        this.iOperations=new IOperation[] { //!! Administrator function implementation!!
                new ExitOperation(),
                new FindOperation(),
                new AddOperation(),
                new DelOperation(),
                new DisplayOperation(),
        };
    }
    public int menu(){
        System.out.println("==========Administrator menu==========");
        System.out.println("hello"+this.name+"Welcome to this system!");
        System.out.println("1.Find books");
        System.out.println("2.New books");
        System.out.println("3.Delete book");
        System.out.println("4.Show books");
        System.out.println("0.Exit the system");
        System.out.println("============================");
        Scanner scanner=new Scanner(System.in);
        int choice=scanner.nextInt();
        return choice;
    }

}

3.3 NormalUser general user class (subclass)

package user;

import operation.*;

import java.util.Scanner;

public class NormalUser extends User{
    public NormalUser(String name) { //Override subclass constructor
        super(name);//Override parent class constructor
        this.iOperations=new IOperation[] {
                new ExitOperation(),
                new FindOperation(),
                new BorrowOperation(),
                new ReturnOperation(),
        };
    }
    public int menu(){
        System.out.println("==========General user menu==========");
        System.out.println("hello"+this.name+"Welcome to this system!");
        System.out.println("1.Find books");
        System.out.println("2.Borrow books");
        System.out.println("3.Return books");
        System.out.println("0.Exit the system");
        System.out.println("============================");
        Scanner scanner=new Scanner(System.in);
        int choice=scanner.nextInt();
        return choice;
    }
}

4. Program entry Main class implementation

import book.BookList;
import user.AdminUser;
import user.NormalUser;
import user.User;

import java.util.Scanner;

/**
 * The entrance of the whole program
 */
public class Main {
 public static User login(){
     System.out.println("Please enter your name:");
     Scanner scanner=new Scanner(System.in);
     String name=scanner.nextLine();
     System.out.println("Please enter your identity: 1->administrators. 0->Ordinary users");
     int choice=scanner.nextInt();
     if (choice==1){ //Implement different user classes according to user selection
         return  new AdminUser(name); 
     }else{
         return new NormalUser(name);
     }

 }

    public static void main(String[] args) {
     BookList bookList=new BookList();
     User user=login(); //Upward Transformation: parent class reference (user) refers to subclass object (AdminUser(name)/NormalUser(name))
     while(true) { //If you exit the system without manual input, the system will continue to cycle
         int choice = user.menu();//A dynamic binding (runtime binding) has occurred
         //Call the appropriate operation according to choice
         user.doWork(choice, bookList);
     }
    }
}

5. Overall code implementation display

After realizing the above four blocks of code, and the Main class connects the functions of each module through upward transformation, our simple library management system has been completed! This is a good exercise project to practice all the knowledge since Java learning. It is worth learning and practicing code repeatedly~

The overall code implementation is shown as follows:

5.1 display of administrator function realization (part)

5.2 ordinary user function realization display (part)

6 end

Here, a simple library management system has been completed~
If you think the blogger's articles are helpful to you, you are welcome to praise and collect more~

Topics: Java Back-end