[Java basic syntax] Dega teaches you to write a library management system in an hour

preface:

Before, I introduced a lot of basic knowledge of Java syntax, but at this time, I feel that I have learned some knowledge, but I still haven't learned it thoroughly. So I wrote a library management system and wrote this article to make my understanding of Java syntax more thorough!

1. Conception

First of all, we should think of the overall framework before knocking. What should a library management system have? At this time, we can imagine going to the library to borrow books

  • Users: people we want to contact with these books (including book borrowers and library administrators). We can construct a User class to build the commonality of this User, inherit this User class through ordinary users and administrators, and improve their respective characteristics
  • Book: the object we want to contact
    • Each book: for all books, we can look for commonalities (book name, author, price, type) to construct a Book class
    • Bookshelf for storing books: if all books are on the bookshelf, then our operations such as checking, borrowing, returning, adding and deleting should be completed with the help of the bookshelf. This is like an array. If we store these books, then the operation of all books only needs to be carried out on this bookshelf. Therefore, we can construct a book order table BookList, and then add a series of operations to complete various functions of the book

At this point, we have users, books and bookshelves, and the connection between them is

Users operate the bookshelf and then affect the state of the book

For the operation of bookshelves, we can actually regard it as the following functions in an abstract way

public void work(BookList bookList);

This function is an abstraction of various operations, so we can abstract the operations on the bookshelf, write an interface Ioperation, and then inherit various functions from this interface. When we operate on the bookshelf, we only need to use the work method to realize different operations

2. Overall framework

Next, let's use it to make a framework diagram, so that when we knock the code, we can improve each part according to this framework

Then let's set up the basic framework according to the idea

3. Analyze each package code

First, I created three new packages according to the frame diagram

  • User (user package)
  • Book (book bag)
  • operation package

2.1 book (book package)

This package contains the contents related to books, including Book class and BookList

2.2.1 separate books (Book type)

To build this class, we first think out the commonalities extracted by ourselves. I myself use the following attributes

Title, author, price, type, lending or not

Next, let's start with the code, because it's relatively simple

public class Book {
    private String name;
    private String author;
    private int price;
    private String type;
    private boolean isLent;

    public String getName() {
        return name;
    }
    
    public boolean isLent() {
        return isLent;
    }

    public void setLent(boolean lent) {
        isLent = lent;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                ", type='" + type + '\'' +
                (isLent?" Not lent":" Lent") +
                '}';
    }

    public Book(String name, String author, int price, String type) {
        this.name = name;
        this.author = author;
        this.price = price;
        this.type = type;
    }
}

Since several member variables defined by me are private, getter and setter methods of some members are created below (some unused getter and setter methods have been deleted personally because they are not used this time)

And the toString method is rewritten, because we will be more comfortable when displaying book information

Finally, a construction method is written, because all kinds of information of the book must be stored when adding a new book

2.2.2 BookList

I personally designed the bookshelf into a sequence table, so what members and methods do we need to use?

  • Number of books deposited
  • Array of books: used to store books
  • Some methods

Look at my code first

public class BookList {
    private int usedSize=3;
    private  Book[] books =new Book[10];
    public  BookList(){
        this.books[0]=new Book("Java Core technology volume I","Cay S.Horstmann",119,"A very expensive book");
        this.books[1]=new Book("Brother bird's Linux Private dishes","Brother bird",118,"A very expensive book");
        this.books[2]=new Book("Sword finger Offer","He Haitao",65,"Expensive books");
    }
    public int getSize(){
        return usedSize;
    }
    public void setSize(int size){
        this.usedSize=size;
    }
    public void setBooks(int pos, Book book){
        books[pos]=book;
    }
    public Book getBook(int pos){
        return books[pos];
    }
}

In the above code, the individual has stored three books first, so the usedSize is 3, and the overall design can store up to 10 books, which can be modified according to different situations

Then there are some methods, including

  • Get the number of books stored: it is used when looking for a book
  • Modify the number of books saved: used when adding and deleting books
  • Get a Book: use it when getting a book
  • Modify a Book: when adding a new book, enter the information of the new book

2.2 operation package for bookshelves

This package class is the operations performed by our users. I personally designed the following operations

Add, delete, find, borrow, return, display all books and exit the system

As for the operation of bookshelves, we can actually abstract it as the following functions

public void work(BookList bookList);

So let's look at the interface code first

2.2.1 operation interface

public interface IOperation {
    public void work(BookList bookList);
}

Interfaces and abstract classes are actually used here

Then we inherit the interface through various operations and improve their contents

2.2.2 new books

public class AddOperation implements IOperation{

    @Override
    public void work(BookList bookList) {
        if(bookList.getSize()==10){
            System.out.println("The library is full and cannot add books");
            return;
        }
        Scanner reader = new Scanner(System.in);
        String name;
        String author;
        int price;
        String type;
        System.out.print("Please enter the title of the book you want to add:");
        name=reader.nextLine();
        System.out.print("Please enter the author of the book:");
        author=reader.nextLine();
        System.out.print("Please enter the price of the book:");
        price=reader.nextInt();
        reader.nextLine();
        System.out.print("Please enter the type of book:");
        type=reader.nextLine();

        int pos=bookList.getSize();
        Book book = new Book(name, author, price, type);
        bookList.setBooks(pos, book);
        bookList.setSize(bookList.getSize()+1);
    }
}

2.2.3 deleting books

public class DelOperation implements IOperation{
    @Override
    public void work(BookList bookList) {
        if(bookList.getSize()==0){
            System.out.println("There are no books in the library, unable to delete");
            return;
        }
        Scanner reader = new Scanner(System.in);
        String name;
        System.out.print("Please enter the title of the book you want to delete:");
        name=reader.nextLine();
        for(int i=0;i<bookList.getSize();i++){
            if(name.equals(bookList.getBook(i).getName())){
                while(bookList.getSize()-i-1!=0){
                    bookList.setBooks(i,bookList.getBook(i+1));
                    i++;
                }
                bookList.setSize(bookList.getSize()-1);
                return;
            }
        }
        System.out.println("There is no such book in the library, unable to delete");
    }
}

2.2.4 finding books

public class FindOperation implements IOperation{
    @Override
    public void work(BookList bookList) {
        if(bookList.getSize()==0){
            System.out.println("There are no books in the library");
            return;
        }
        Scanner reader = new Scanner(System.in);
        String name;
        System.out.print("Please enter the title of the book you want to find:");
        name=reader.nextLine();
        for(int i=0;i<bookList.getSize();i++){
            if(name.equals(bookList.getBook(i).getName())){
                System.out.println("The book has been found with the following information:");
                System.out.println(bookList.getBook(i));
                return;
            }
        }
        System.out.println("The book was not found");
    }
}

2.2.5 borrowing books

public class LendOperation implements IOperation{
    @Override
    public void work(BookList bookList) {
        if(bookList.getSize()==0){
            System.out.println("There are no books in the library. You can't borrow them");
            return;
        }
        Scanner reader = new Scanner(System.in);
        String name;
        System.out.print("Please enter the title of the book you want to borrow:");
        name=reader.nextLine();
        for(int i=0;i<bookList.getSize();i++){
            if(name.equals(bookList.getBook(i).getName())){
                if(bookList.getBook(i).isLent()==false) {
                    bookList.getBook(i).setLent(true);
                    System.out.println("Borrowing succeeded");
                }else{
                    System.out.println("The book has been borrowed by others, failed to borrow");
                }
                return;
            }
        }
        System.out.println("The book is not found, borrowing failed");
    }
}

2.2.6 returning books

public class ReturnOperation implements IOperation{
    @Override
    public void work(BookList bookList) {
        Scanner reader = new Scanner(System.in);
        String name;
        System.out.print("Please enter the title of the book you want to return:");
        name=reader.nextLine();
        for (int i =0;i<bookList.getSize();i++){
            if(name.equals(bookList.getBook(i).getName())){
                if(bookList.getBook(i).isLent()==true){
                    bookList.getBook(i).setLent(false);
                    System.out.println("The book was returned successfully");
                    return;
                }else{
                    System.out.println("The book was not borrowed, operation error");
                    return;
                }
            }
        }
        System.out.println("The book you want to return is not found, operation error");
    }
}

2.2.7 display all book information

public class DisplayOperation implements IOperation{
    @Override
    public void work(BookList bookList) {
        if(bookList.getSize()==0){
            System.out.println("There are no books in the library");
        }
        for(int i=0;i<bookList.getSize();i++){
            System.out.println(bookList.getBook(i));
        }
    }
}

2.2.8 exit the system

public class ExitOperation implements IOperation{
    @Override
    public void work(BookList bookList) {
        System.out.println("The library management system has exited. Welcome to use it next time!");
        System.exit(0);
    }
}

The above specific operations are actually a series of operations on a sequence table. When you think about them, you will find that they are a relatively simple part of the whole project

2.3 user (user package)

This package contains the users I want to construct (administrators and ordinary users), so I created the parent User first. What is a User's basic information?

  • user name
  • Menu: we imagine that when we go to the ATM to withdraw money, we can see an interface
  • Actions to be performed by the user

Then let's look at my code first!

2.3.1 User class

abstract public class User {
    protected String name;
    protected IOperation[] iOperations;

    public User(String name) {
        this.name = name;
    }

    abstract public int menu();

    public void doOperation(int choice, BookList bookList){
        iOperations[choice].work(bookList);
    }
}

At this point, you will find that in addition to the definition of user name, other attributes and behaviors have some details to think about

  • Menu: because the menus of ordinary users and administrators are different, and we don't need a parent class to implement specific code, I modified it into an abstract class

  • What users should do: in fact, it is easy to understand the code in the above code when integrating the framework

    protected IOperation[] iOperations;
    
    public void doOperation(int choice, BookList bookList){
        iOperations[choice].work(bookList);
    }
    

    Because we need users to perform these operations, the interface I personally designed for ordinary users and administrators is actually as shown in the figure below

    So I first created an array of operations. Note that I did not create an object at this time, because the objects (i.e. operations) of ordinary users and administrators are different. You can see from the above menu. Then, a method (that is, the method used by the user to call the operation) is constructed to pass in the sequence number of the corresponding operation and the object to be operated, so as to realize the use of these operations

Now, the definition of administrators and ordinary users is also very simple, that is, to modify the objects of menus and operation arrays

2.3.2 AdminUser class

public class AdminUser extends User{
    public AdminUser(String name){
        super(name);
        this.iOperations = new IOperation[]{new ExitOperation(), new FindOperation(), new AddOperation(), new DelOperation(), new DisplayOperation()};
    }

    public int menu(){
        System.out.println("========= Administrator menu =========");
        System.out.println("1: Find books");
        System.out.println("2: New books");
        System.out.println("3: Delete book");
        System.out.println("4: Show all books");
        System.out.println("0: Exit the system");
        System.out.print("Please enter the sequence number of the operation you want to perform:");
        Scanner reader = new Scanner(System.in);
        int index = reader.nextInt();
        return index;
    }
}

2.3.3 NormalUser class

public class NormalUser extends User{
    public NormalUser(String name){
        super(name);
        this.iOperations = new IOperation[]{new ExitOperation(), new FindOperation(), new LendOperation(), new ReturnOperation()};
    }

    public int menu(){
        System.out.println("========= User menu =========");
        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.print("Please enter the sequence number of the operation you want to perform:");
        Scanner reader = new Scanner(System.in);
        int index = reader.nextInt();
        return index;
    }
}

4. Integration code (including main class code)

In fact, when I write code, it is certainly impossible for me to put all the details in place in one step. I must write and change under the big framework.

Now that we have the code of the above packages, how can we integrate them in the main class? Go straight to the code first

public class Main {
    public static User login(){
        System.out.println("========= Library management system =========");
        System.out.print("Please enter your name:");
        Scanner reader = new Scanner(System.in);
        String name = reader.nextLine();
        System.out.println("welcome " + name + " Login system");
        System.out.println("Are you an administrator (0) or an ordinary user (1):");
        int choice = reader.nextInt();
        if(choice==0){
            return new AdminUser(name);
        }else{
            return new NormalUser(name);
        }
    }
    public static void main(String[] args) {
        BookList bookList = new BookList();
        User user = login();
        while(true){
            int choice=user.menu();
            user.doOperation(choice, bookList);
        }
    }
}

Let's look at the main method first. The bookshelf is a warehouse that covers all the books in the book system, so we must construct it first.

Suppose we go to the bank to withdraw money, then this bookshelf is equivalent to building a bank first. Then, when we come to the ATM, the next step is to insert a card for login, so our library management system is the same. We need to make a login style, that is, I created a login method. The code is easy to understand. The return value of this method is the user (the idea of polymorphism and dynamic binding is used here)

After logging in, a user's menu interface will appear, that is, the menu of the above code, which is why the code in the user menu finally asks us to enter the operation sequence number to be executed, and the doubt that the return value is int.

Finally, we perform the corresponding operation according to the obtained operation sequence number!

5. Summary (colored egg)

So far, I believe you have a general understanding of the system in the library. If you still have doubts, it is actually a matter of hand coding. Before I wrote this management system, I also felt it was a little difficult, but after you conceived the framework, in fact, your cornerstone was almost laid. The rest of the code should be done in an hour!

For me personally, at least the knowledge I learned before seems a little more practical. And with the expansion of my knowledge, this library management system will have a higher-level version waiting to be released. You can look forward to it!

Tags: Java JavaSE

Posted on Sat, 25 Sep 2021 13:39:18 -0400 by websesame