Java Small example: library curriculum Design (Java version 8)

Source: Internet
Author: User

Simulate a library with Java. This includes features such as creating books, creating readers, borrowing books, returning books, listing all of them, listing all readers, listing borrowed books, and listing books that have expired. Each reader can borrow up to 3 books, each book can only be borrowed for 3 weeks, more than even if it expires.

This example adds Java 8-specific syntax compared to http://blog.csdn.net/yidinghe/article/details/3940437, including: Lambda expression, Java.time date API, Streaming API and so on. function is also slightly better than the former, the volume has decreased.

Import Java.time.localdate;import Java.time.format.datetimeformatter;import Java.time.temporal.chronounit;import Java.util.arraylist;import Java.util.arrays;import Java.util.list;import Java.util.scanner;import Java.util.concurrent.atomic.atomicinteger;import Java.util.function.supplier;import java.util.stream.Collectors /** * Library Example Java 8 version * created at 2014/11/4 * * @author yiding */public class LibraryManager {public static final Sc    Anner SCANNER = new SCANNER (system.in); public static final String numbers_only = "^\\d+$";  Indicates that only digital public is allowed to enter static final String any_content = "^\\s+$";    Indicates that any content can be entered public static void main (string[] args) {new LibraryManager (). Start ();    }////////////////////////////////////////////////////////////////Private Library library = new Library ();    Private arraylist<command> commands = new arraylist<> ();    Private String MainMenu;     /** * Construction Method */Public LibraryManager () {initcommands ();   Initstudents ();    Initbooks ();        } private void Initbooks () {This.library.addBook ("on the Programmer's self-cultivation", "Cutlass", BookType. Science. toString ());        This.library.addBook ("The Complete works of the four major masterpieces of India", "adalimumab", BookType. Literature category. ToString ());        This.library.addBook ("The Benefits of Sleep", "Programmer Dee", BookType. Scientific class. ToString ());    This.library.addBook ("October 2014 edition of Architects", "Beautiful Women's Web", BookType Magazine. toString ());        } private void Initstudents () {This.library.students.add (New Student ("Zhang San"));        This.library.students.add (New Student ("John Doe"));    This.library.students.add (New Student ("Harry")); }/** * Initialize command and main Menu */private void Initcommands () {AddCommand ("All Books:", ()-&G T        library.books), "Search All Books");        AddCommand (New listcommand<> ("All Students:", (), library.students), "Enquiry for All Students");        AddCommand (New Addbookcommand (), "Add Book");        AddCommand (New Deletebookcommand (), "delete book");        AddCommand (New Borrowbookcommand (), "borrowing books"); AddCommand (New returnbookcomMand (), "return book");        AddCommand (New listcommand<> ("All borrowing expired books:", library::expiredbooks), "Check borrowing of expired books");        AddCommand (New Exitcommand (), "exit");    This.mainmenu = Tomenu ("Please enter Command", this.commands);        } private void AddCommand (Command command, String title) {command.title = title;    This.commands.add (command);        }/** * begins interactive */private void Start () {Commandresult result;                In the while condition, determine whether the execution result of the command indicates that you want to exit the program//only exitcommand The execution result is commandresult.exit do {try { String command = prompt (MainMenu, numbers_only);                Select command result = ExecuteCommand (command);            Execute command} catch (Commandcancelexception e) {result = Commandresult.fail;        } System.out.println (result.prompt + "\ n");    } while (Result! = Commandresult.exit); /** * Print a prompt message and return the user's input * * @param prompt prompt message * @param pattern specified format if the user's input is not qualifiedRepeatedly prompts for re-entry. Null does not check user input * * @return user input */private String prompt (string prompt, String pattern) {string Userin        Put Determines whether the user-entered content in the while condition conforms to the format specified by pattern//if pattern is NULL then do not judge do {System.out.print (prompt            );            Userinput = Scanner.nextline ();            When the user returns directly, the Cancel command executes if (Userinput.equals ("")) {throw new commandcancelexception ();        }} while (pattern! = null &&!userinput.matches (pattern));    return userinput; }//Print a set of options and return the user-selected option content private string prompt (String prompt, list<?> options) {int index = Promptindex        (prompt, options);    Return Options.get (index-1). toString (); }//Print a set of options and return the user's chosen location private int Promptindex (String prompt, list<?> options) {String menu = Tomenu (pr        Ompt, Options);        int index;        do {index = Integer.parseint (Prompt (menu, numbers_only)); } while (index = =0 | |        Index > Options.size ());    return index;    /** * Generate Menu Contents * * @param prompt prompt, print out after listing all options * @param options * * @return Main Menu Contents */ Private <T> string Tomenu (String prompt, list<t> options) {final arraylist<string> lines = NE        W arraylist<> ();        Final Atomicinteger counter = new Atomicinteger ();            Options.foreach (t), {int index = Counter.incrementandget ();            String line = index + ":" + t.tostring ();        Lines.add (line);        });    return String.Join ("\ n", lines) + "\ n" + Prompt + "(1-" + lines.size () + "):"; /** * Execute user command * * @param command User order number * * @return Execution result */private Commandresult Executeco        Mmand (String command) {int index = integer.parseint (command);        if (Index > 0 && index <= commands.size ()) {return Commands.get (index-1). Execute (); } else {return commanDresult.ok; }}////////////////////////////////////////////////////////////////static enum Commandresult {OK ("command completed 。 "), FAIL (" The command has been canceled.)        "), EXIT (" ");   public String prompt;        At the end of each command, print out Commandresult (String prompt) {this.prompt = prompt; }} static enum BookType {Literature class, Science class, Magazine}//Represents the exception of the user cancel command static class Commandcancelexception extends Runtimeexce        ption {} Static class book {public static final int expire_borrow_days = 21;        public String name;        public String author;        public String type;        Public String Borrowedby;        Public String borrowdate;            Book (string name, string author, String type) {this.name = name;            This.author = author;        This.type = type;        } public boolean isborrowed () {return this.borrowedby! = NULL; } @Override Public String toString () {return name + "," + author + "," + Type + (isborrowed ()?        "--Has been '" + Borrowedby + "' on" + Borrowdate + "lent": "");            public boolean isexpired () {if (!isborrowed ()) {return false; }//Reverse expired borrowing time from the current time.             If the actual borrowing time is before the expired borrowing time, the localdate maxborrowdate = Localdate.now () is expired. Minus (Expire_borrow_days, chronounit.days);            String maxborrowdatestr = Datetimeformatter.ofpattern ("YyyyMMdd"). Format (maxborrowdate);        Return This.borrowDate.compareTo (MAXBORROWDATESTR) < 0;        }} static class Student {public static final int max_borrow = 3;        public String name;        Student (String name) {this.name = name;        } @Override Public String toString () {return name; }}////////////////////////////////////////////////////////////////class Library {private list<book& Gt        Books = new Arraylist<> (); Private list<student> Students = new arraylist<> ();         /** * Add Book * * @param bookname title * @param author author * @param type            * * @return Execution result */public Commandresult Addbook (string bookname, string author, String type) { if (Books.stream (). AnyMatch ((b), B.name.equals (BookName)) {System.out.println ("Add failed: Title already exists"                );            return commandresult.fail;            } this.books.add (new book (BookName, author, type));        return Commandresult.ok; } public list<book> Availablebooks () {return This.books.stream (). Filter ((b),!b.isborrowed ()        ). Collect (Collectors.tolist ()); Public list<book> Borrowedbooks () {return This.books.stream (). Filter (book::isborrowed). Collect (        Collectors.tolist ()); Public list<book> Expiredbooks () {return This.books.stream (). Filter (book::isexpired). CollecT (Collectors.tolist ()); }/** * Delete book * * @param index number * * @return Execution result */public            Commandresult deletebook (int index) {this.books.remove (index);        return Commandresult.ok; } public int countborrowedbooks (String student) {return (int) This.books.stream (). Filter ((b), stud        Ent.equals (B.borrowedby)). Count ();  }}/////////////////////////////////////////////////////////////////** * represents an abstract class of commands */static abstract  Class Command {public String title;        Command title, which will be displayed in the main menu, Abstract Commandresult execute ();        @Override public String toString () {return title; }}//Lists the objects that meet the requirements class Listcommand<t> extends Command {private supplier<list<t>> Suppli Er               The method that queries the object that satisfies the requirement private String title; Output title Listcommand (String title, supplier<list<t>>Supplier) {this.title = title;        This.supplier = supplier;            } @Override Commandresult Execute () {System.out.println ("\ n" + title);            Supplier.get (). ForEach (System.out::p rintln);        return Commandresult.ok; }}//Add Book Class Addbookcommand extends Command {@Override Commandresult execute () {R                     Eturn Library.addbook (Prompt ("Please enter the title:", Any_content), Prompt ("Please enter Author:", Any_content),        Prompt ("Please select book type:", Arrays.aslist (Booktype.values ()));            }}//delete book class Deletebookcommand extends Command {@Override Commandresult execute () { if (Library.books.isEmpty ()) {System.out.println ("There is no book to delete.                ");            return commandresult.fail;            } int index = Promptindex ("Please select book serial number", library.books);        Return Library.deletebook (index-1);  }  }//Borrowing Books class Borrowbookcommand extends Command {@Override Commandresult execute () {L            ist<book> availablebooks = Library.availablebooks (); if (Availablebooks.isempty ()) {System.out.println ("no books to borrow.                ");            return commandresult.fail;            } int index = Promptindex ("Please select books to borrow", availablebooks);            Book book = Availablebooks.get (index-1);            String student = prompt ("Please select borrower:", library.students); if (Library.countborrowedbooks (student) >= Student.max_borrow) {System.out.println ("the classmate can't borrow more books.                ");            return commandresult.fail;            } String bdate = prompt ("Please enter the borrowing date (YYYYMMDD):", "^\\d{8}$");            Book.borrowedby = student;            Book.borrowdate = bdate;        return Commandresult.ok;      }}//Return book Class Returnbookcommand extends Command {@Override Commandresult execute () {      list<book> borrowedbooks = Library.borrowedbooks (); if (Borrowedbooks.isempty ()) {System.out.println ("No book needs to be returned.")                ");            return commandresult.fail;            } int index = Promptindex ("Please select Borrowed books", borrowedbooks);            Book book = Borrowedbooks.get (index-1);            Book.borrowedby = null;            Book.borrowdate = null; System.out.println ("The book has been returned.            ");        return Commandresult.ok; }}//Exit Program class Exitcommand extends Command {@Override Commandresult execute () {Retu        RN Commandresult.exit; }    }}


Java Small example: library curriculum Design (Java version 8)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.