Java 图书馆计划 - 分配和借书

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34086737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:17:46  来源:igfitidea点击:

Library Program - Assigning & checking out books

javaeclipsestring

提问by kayylai

I'm supposed to create a library program in java that allows you to create patrons and check out a maximum of 3 books. I'm really beginner at java so I apologize that my code is all over the place and may not make sense.

我应该用 Java 创建一个图书馆程序,它允许您创建顾客并检查最多 3 本书。我真的是 Java 的初学者,所以我很抱歉我的代码到处都是,可能没有意义。

Below is the library class that I attempted(i also have a separate Patron, Book and Book Interface class) My main concerns:

下面是我尝试的图书馆类(我还有一个单独的读者、书籍和书籍接口类)我的主要关注点:

  • I have 2 ArrayLists, one for a list of inputed Users and another for a list of inputed Books. However how would i be able to assign certain checked out books to a certain user & make sure they borrow no more than 3?

  • I put a lot of the code in the main method but i end up having a lot of problems with static and non static stuff

  • How would I be able to create status' for each book? for example if "great expectations" is checked out, how can assign "borrowed" to it and make sure no one else can borrow it?

  • 我有 2 个 ArrayList,一个用于输入用户列表,另一个用于输入书籍列表。但是,我如何才能将某些已借出的图书分配给某个用户并确保他们借出的图书不超过 3 册?

  • 我在 main 方法中放了很多代码,但最终我遇到了很多静态和非静态内容的问题

  • 我如何能够为每本书创建状态?例如,如果签出“很高的期望”,如何将“借用”分配给它并确保没有其他人可以借用它?

The program runs so far but its lacking depth because I'm lost as to how to check out/in books under a certain specified patron.

该程序运行至今,但缺乏深度,因为我不知道如何在某个指定的赞助人下签出/签入书籍。

SORRY again for all the inconsistencies in my code and i really really appreciate the help!

再次对我的代码中的所有不一致表示抱歉,我真的非常感谢您的帮助!

import java.awt.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner; 
import java.util.Collections; 
public class Library 
{


 static ArrayList <Patron> UserList = new ArrayList<Patron>();
 static ArrayList <String> BookList = new ArrayList <String> (); 
 
 public static String status;
 public static String borrower; 
 public static String borrowDate; 
 public static String returnDate; 
 public String status1 = "Available";
 public String status2 = "Borrowed";
 
 
 public static void main(String[] args)
 {
  Scanner input = new Scanner(System.in);
  int choice = 0;
  System.out.println("********************Welcome to the Public Library!********************");
  System.out.println("              Please Select From The Following Options:               ");
  System.out.println("**********************************************************************");
  
  while(choice != 9)
  {
   System.out.println("1: Add new patron");
   System.out.println("2: Add new book");
   System.out.println("3: Edit patron");
   System.out.println("4: Edit book");
   System.out.println("5: Display all patrons");
   System.out.println("6: Display all books");
   System.out.println("7: Check out book");
   System.out.println("8: Check in book");
   System.out.println("9: Search book");
   System.out.println("10: Search Patron");
   System.out.println("9: Exit");
   choice = input.nextInt();

   
  switch(choice)
  {
  case 1: //Add new patron
   System.out.print("Enter patron first name: ");
   String firstName = input.next(); //read name from input
   System.out.print("Enter patron last name: ");
   String lastName = input.next(); 

   UserList.add(new Patron(firstName, lastName)); //add name to list
   System.out.println("-----You have successfully added a new patron!-----");
   break; 
       
  case 2: //Add new book
   System.out.print("Enter book title: ");
   String title1 = input.next();
    
   Scanner input1 = new Scanner(System.in);
   System.out.print("Enter book author: ");
   String author1 = input.next(); 

   Book book1 = new Book(title1);    
   BookList.add(title1);
   FullBookList.add(fullBook);
   System.out.println("-----You have successfully added a new book!-----");
   
   status = "available";
   borrowDate = "none";
   returnDate = "none";
   borrower = "none";
   
   break; 
   
  case 3: //Edit patron name
   System.out.println("Enter original patron name: ");
   String originalName = input.next(); 
   System.out.println("Enter edited patron name: ");
   String editedName = input.next(); 
   //Collections.replaceAll(UserList, originalName, editedName);
   if(UserList.contains(originalName))
   {
    
   }
    
  case 4: //edit book
   
   
  case 5: //display all patrons 
    System.out.println(UserList); 
    break; 
    
  case 6: //display all books 
    System.out.println(BookList); 
    break; 
    
  case 7: //check out a book
    Patron.CheckOutBook(); 
    break; 
  case 8: //check in a book
    Patron.CheckInBook(); 
    break; 
    
   
   }
  }
 }
}

import java.util.ArrayList;
import java.util.Scanner;

public class Patron 
{
 Scanner input = new Scanner(System.in);
 private String first; 
 private String last; 
 int bookCount = 0; //amount books user has in pocket
 int books = 0;
 
 
 //constructor to "add new patron" by entering their name. 
 public Patron(String f, String l)
 {
  first = f; 
  last = l; 
 }
 
 public String toString()
 {
  return first + " " + last; 
 }
 
 public String getName() 
 {
  return first +  " " + last; 
 }

 public static void CheckOutBook()
 {
  System.out.println("Enter book title to be check out: ");
  Scanner input = new Scanner(System.in);
  String bookCheckOut = input.next(); 
  if(Library.BookList.contains(bookCheckOut))
  {
   Library.BookList.remove(bookCheckOut);
   System.out.println("-----" + bookCheckOut + " has been checked out!-----");
   System.out.println ("-------" + bookCheckOut + " is due in 7 days!-------");
       
  }
  else 
   System.out.println(bookCheckOut + " is not in the library. Please enter "
   + "a different book to be checked out");
  
 }
 
 public static void CheckInBook()
 {
  System.out.println("Enter book title to be checked in: ");
  Scanner input = new Scanner(System.in);
  String bookCheckIn = input.next(); 
  if(Library.BookList.contains(bookCheckIn))
  {
   Library.BookList.add(bookCheckIn);
   System.out.println("-----" + bookCheckIn + " has been checked in!-----"); 
       
  }
  else 
   System.out.println(bookCheckIn + " is not in the library. Please enter "
   + "a different book to be checked out");
 }
 
 public boolean canBorrow()
 {
  if(bookCount <= 3)
  {
   return true; 
  } 
  else 
  {
   return false; 
  }
 }

}

采纳答案by D. Ben Knoble

Note: This will likely involve some refactoring to your main loop.

注意:这可能涉及对主循环的一些重构。

Alright so the way I see it, we have three classes at play here: some Patrons, which can check books out and in, some Books, which have statuses like "available" and "checked out," and a Library, which contains books. So, we need 3 classes:

好吧,在我看来,我们这里有三个类在起作用:一些读者,可以签出和签入书籍,一些书籍,其状态为“可用”和“已签出”,以及一个图书馆,其中包含书籍. 所以,我们需要3个类:

I'll start with Book and use pseudo code to explain the concepts for you to implement.

我将从本书开始,并使用伪代码来解释您要实现的概念。

class Book
{
    //private fields
    private final String title;
    private final String author;
    private Status available = true;
    //note--i would prefer using an Enum called status for this, 
    //but a boolean true/false value works adequately

    //Constructor
    public Book(string title, string author) {}

    //accessors for title, author, available
    //setter for available--used for Library only--there are better ways to ensure
    //Patrons can't set the status of the book, but for now this is the simplest way
}

As you can see, Books have immutable fields that don't need to change, and one field that tracks it status. A better implementation might make Library track book status, as that makes more logical sense and better code, but this a simple implementation.

如您所见,Books 具有不需要更改的不可变字段,以及一个跟踪其状态的字段。更好的实现可能会使图书馆跟踪簿状态,因为这更符合逻辑意义和更好的代码,但这是一个简单的实现。

Next, Library, which needs lots of books:

接下来是需要大量书籍的图书馆:

class Library
{
    private final ArrayList<Book> books;

    //Constructor
    public Library ()
    {
        books = loadBooks();
    }

    //some methods
    private ArrayList<Book> loadBooks () {}
    //however you want to create all your books (file input, whatever)

    public bool isBookAvailable (Book b)
    {
        if b isn't in library: return false
        else return (b in books).isAvailable()
    }

    public Book checkoutBook (Book b)
    { get book (checking availability, possibly returning a null Book), set status to unavailable, return it }

    public Book checkinBook (Book b)
    { check that this the book belongs to library, set status to available }
}

As I said earlier, this isn't perfect. I could spend quite some time going on and on about how to improve the design, but for the sake of simplicity won't.

正如我之前所说,这并不完美。我可以花相当多的时间继续讨论如何改进设计,但为了简单起见不会。

Now, Patrons. One question is, should Patrons have only one library that the visit? Or do they visit multiple libraries? I'll assume they visit more than one, since sometimes a library doesn't have all the books you want.

现在,赞助人。一个问题是,赞助人是否应该只访问一个图书馆?或者他们访问多个图书馆?我假设他们访问不止一个,因为有时图书馆没有你想要的所有书籍。

class Patron
{
    private final String name;
    private final Book[] books = new Book[3];//you can see I'm limiting them to 3 books
    private int index = 0;

    //Constructor
    public Patron (String name) {}

    //methods
    public void checkoutBook (Book b, Library l)
    {//could be tricky
        check books status in l (l.isBookAvailable(b))
        if available: 
            if space (index < 2) Book newBook = l.checkoutBook(b); books[index++] = newBook;
            else: no space
        else: not available
    }

    public void checkinBook (int bookIndex, Library l)
    {
         if bookIndex < 3:
             if books[index] != null:
                 l.checkinBook (books[index]);
                 books[index--] = null;
             else: no book
         else: not valid index
    }
}

Of course, other utilities like displaying books (library, patron) and toString methods might be useful. But now the responsibility of the main method is to create some patrons, a library, and give patrons the chance to check out and check in books via a menu. You have the heavy lifting done; you can work on input and output now.

当然,其他实用程序,如显示书籍(图书馆、赞助人)和 toString 方法可能很有用。但现在主要方法的职责是创建一些顾客,一个图书馆,并让顾客有机会通过菜单签出和签入书籍。你已经完成了繁重的工作;您现在可以处理输入和输出。

Any questions?

任何问题?

回答by Kh Ahmed

A Beginner Level "Student Library Program" in JAVA, which interacts the Students and the Books. This Library Program can do following functions:

JAVA 中的初级“学生图书馆计划”,它使学生和书籍互动。该库程序可以执行以下功能:

1-Adding a Book to Library.

1-将一本书添加到图书馆。

2-Update Book Quantity.

2-更新图书数量。

3-Search a Book with its Serial number.

3-用它的序列号搜索一本书。

4-Search Books With Author Name.

4-搜索带有作者姓名的书籍。

5-Show all Books and their related Information.

5-显示所有书籍及其相关信息。

6-Registering a Student.

6-注册学生。

7-Show All Registered Students.

7-显示所有注册学生。

8-Student can Check Out Book From Library(if registered).

8-学生可以从图书馆借书(如果注册)。

:- Student can not Check Out more than 3 Books

:- 学生不能借出超过 3 本书

:- You can only borrow a Book If it is Available in Library

:- 你只能借一本书,如果它在图书馆可用

9-Student can Check In Book to Library.

9-学生可以在图书馆登记。

10-You can also see the Books which a Student has Checked Out(only while checking in)

10-您还可以看到学生已签出的书籍(仅在签入时)

Note: At the time it can store only 50 books for simlicity in program

I Have created this program with the maximum skill and knowledge i had in java. As I'm a Beginner so I couldn't do more

我用我在 Java 中拥有的最高技能和知识创建了这个程序。因为我是初学者所以我不能做更多



Kindly give reviews about Program

请给予有关程序的评论

Also tell me refinements which are to be made in program

还告诉我要在程序中进行的改进

Kindly Tell me the better way to do this Program

请告诉我执行此程序的更好方法



package library;

import java.util.Scanner;



public class book {

public int sNo;
public String bookName;
public String authorName;
public int bookQty;
public int bookQtyCopy;

Scanner input = new Scanner(System.in);

public book(){

    System.out.println("Enter Serial No of Book:");
    this.sNo = input.nextInt();
    input.nextLine();
    System.out.println("Enter Book Name:");
    this.bookName = input.nextLine();
    System.out.println("Enter Author Name:");
    this.authorName = input.nextLine();
    System.out.println("Enter Quantity of Books:");
    this.bookQty = input.nextInt();
    bookQtyCopy = this.bookQty;

}

}


package library;

import java.util.Scanner;

public class books {

book theBooks[] = new book[50];     // Array that stores 'book' Objects.
public static int count;    // Counter for No of book objects Added in Array.

Scanner input = new Scanner(System.in);




public int compareBookObjects(book b1, book b2){

    if (b1.bookName.equalsIgnoreCase(b2.bookName)){

        System.out.println("Book of this Name Already Exists.");
        return 0;

    }
    if (b1.sNo==b2.sNo){

        System.out.println("Book of this Serial No Already Exists.");
        return 0;
    }
    return 1;
}

public void addBook(book b){

    for (int i=0; i<count; i++){

        if (this.compareBookObjects(b, this.theBooks[i]) == 0)
            return;

    }

    if (count<50){

        theBooks[count] = b;
        count++;

    }
    else{

        System.out.println("No Space to Add More Books.");

    }

}

public void searchBySno(){

    System.out.println("\t\t\t\tSEARCH BY SERIAL NUMBER\n");

    int sNo;
    System.out.println("Enter Serial No of Book:");
    sNo = input.nextInt();

    int flag = 0;
    System.out.println("S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");
    for (int i=0; i<count; i++){

        if (sNo == theBooks[i].sNo){

            System.out.println(theBooks[i].sNo + "\t\t" + theBooks[i].bookName + "\t\t" + theBooks[i].authorName + "\t\t" + 
                theBooks[i].bookQtyCopy + "\t\t" + theBooks[i].bookQty);
            flag++;
            return;

        }

    }
    if (flag == 0)
        System.out.println("No Book for Serial No " + sNo + " Found.");

}

public void searchByAuthorName(){

    System.out.println("\t\t\t\tSEARCH BY AUTHOR'S NAME");
    input.nextLine();
    System.out.println("Enter Author Name:");
    String authorName = input.nextLine();
    int flag = 0;
    System.out.println("S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");
    for (int i=0; i<count; i++){

        if (authorName.equalsIgnoreCase(theBooks[i].authorName)){

            System.out.println(theBooks[i].sNo + "\t\t" + theBooks[i].bookName + "\t\t" + theBooks[i].authorName + "\t\t" + 
                theBooks[i].bookQtyCopy + "\t\t" + theBooks[i].bookQty);
            flag++;
        }

    }
    if (flag == 0)
        System.out.println("No Books of " + authorName + " Found.");

}


public void showAllBooks(){

    System.out.println("\t\t\t\tSHOWING ALL BOOKS\n");
    System.out.println("S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");
    for (int i=0; i<count; i++){

        System.out.println(theBooks[i].sNo + "\t\t" + theBooks[i].bookName + "\t\t" + theBooks[i].authorName + "\t\t" + 
                theBooks[i].bookQtyCopy + "\t\t" + theBooks[i].bookQty);


    }

}

public void upgradeBookQty(){

    System.out.println("\t\t\t\tUPGRADE QUANTITY OF A BOOK\n");
    System.out.println("Enter Serial No of Book");
    int sNo = input.nextInt();
    for (int i=0; i<count; i++){

        if (sNo == theBooks[i].sNo){

            System.out.println("Enter No of Books to be Added:");
            int addingQty = input.nextInt();
            theBooks[i].bookQty += addingQty;
            theBooks[i].bookQtyCopy += addingQty;
            return;

        }

    }

}


public void dispMenu(){

    System.out.println("----------------------------------------------------------------------------------------------------------");
    System.out.println("Enter 0 to Exit Application.");
    System.out.println("Enter 1 to Add new Book.");
    System.out.println("Enter 2 to Upgrade Quantity of a Book.");
    System.out.println("Enter 3 to Search a Book.");
    System.out.println("Enter 4 to Show All Books.");
    System.out.println("Enter 5 to Register Student.");
    System.out.println("Enter 6 to Show All Registered Students.");
    System.out.println("Enter 7 to Check Out Book. ");
    System.out.println("Enter 8 to Check In Book");
    System.out.println("------------------------------------------------------------- 
   ---------------------------------------------");

}

public int isAvailable(int sNo){

    //returns the index number if available



    for (int i=0; i<count; i++){

        if (sNo == theBooks[i].sNo){
            if(theBooks[i].bookQtyCopy > 0){

                System.out.println("Book is Available.");
                return i;

            }
            System.out.println("Book is Unavailable");
            return -1;

        }

    }

    System.out.println("No Book of Serial Number " + " Available in Library.");
    return -1;


}

public book checkOutBook(){

    System.out.println("Enter Serial No of Book to be Checked Out.");
    int sNo = input.nextInt();

    int bookIndex =isAvailable(sNo);

    if (bookIndex!=-1){

        //int bookIndex = isAvailable(sNo);
        theBooks[bookIndex].bookQtyCopy--;

        return theBooks[bookIndex];
    }

    return null;

}

public void checkInBook(book b){

    for (int i=0; i<count; i++){

        if (b.equals(theBooks[i]) ){

            theBooks[i].bookQtyCopy++;
            return;

        }

    }

}







 }


package library;

import java.util.Scanner;    
public class student {

String studentName;
String regNum;

book borrowedBooks[] = new book[3];
public int booksCount = 0;

Scanner input = new Scanner(System.in);

public student(){

    System.out.println("Enter Student Name:");
    this.studentName = input.nextLine();

    System.out.println("Enter Reg Number:");
    this.regNum = input.nextLine();

}
}


package library;

import java.util.Scanner;

public class students {

Scanner input = new Scanner(System.in);

student theStudents[] = new student[50];

//books book;


public static int count = 0;

public void addStudent(student s){

    for (int i=0; i<count; i++){

        if(s.regNum.equalsIgnoreCase(theStudents[i].regNum)){

            System.out.println("Student of Reg Num " + s.regNum + " is Already Registered.");
            return;
        }

    }

    if (count<=50){

        theStudents[count] = s;
        count++;

    }

}
public void showAllStudents(){

    System.out.println("Student Name\t\tReg Number");
    for (int i=0; i<count; i++){

        System.out.println(theStudents[i].studentName + "\t\t" + theStudents[i].regNum);

    }


}

public int isStudent(){
    //return index number of student if available

     //System.out.println("Enter Student Name:");
    //String studentName = input.nextLine();

    System.out.println("Enter Reg Number:");
    String regNum = input.nextLine();

    for (int i=0; i<count; i++){

        if (theStudents[i].regNum.equalsIgnoreCase(regNum)){

            return i;

        }

    }
    System.out.println("Student is not Registered.");
    System.out.println("Get Registered First.");


    return -1;

}
public void checkOutBook(books book){
    int studentIndex =this.isStudent();

    if (studentIndex!=-1){
        System.out.println("checking out");

        book.showAllBooks();//jjjjjjjjjjjj
        book b = book.checkOutBook();
        System.out.println("checking out");
        if (b!= null){

            if (theStudents[studentIndex].booksCount<=3){
                System.out.println("adding book");
                theStudents[studentIndex].borrowedBooks[theStudents[studentIndex].booksCount] = b;
                theStudents[studentIndex].booksCount++;
                return;

            }
            else {

                System.out.println("Student Can not Borrow more than 3 Books.");
                return;

            }
        }
        System.out.println("Book is not Available.");

    }

}

public void checkInBook(books book){

    int studentIndex = this.isStudent();
    if (studentIndex != -1){
        System.out.println("S.No\t\t\tBook Name\t\t\tAuthor Name");
        student s = theStudents[studentIndex];
        for (int i=0; i<s.booksCount; i++){

            System.out.println(s.borrowedBooks[i].sNo+ "\t\t\t" + s.borrowedBooks[i].bookName + "\t\t\t"+
                    s.borrowedBooks[i].authorName);

        }
        System.out.println("Enter Serial Number of Book to be Checked In:");
        int sNo = input.nextInt();
        for (int i=0; i<s.booksCount; i++){

            if (sNo == s.borrowedBooks[i].sNo){

                book.checkInBook(s.borrowedBooks[i]);
                s.borrowedBooks[i]=null;
                return;

            }


        }
        System.out.println("Book of Serial No "+sNo+"not Found");

    }



}


}


package library;

import java.util.Scanner;

public class Library {


public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.println("********************Welcome to the Student Library!********************");
    System.out.println("              Please Select From The Following Options:               ");
System.out.println("**********************************************************************");
    books ob = new books();
    students obStudent = new students();
    int choice;
    int searchChoice;

    do{

        ob.dispMenu();
        choice = input.nextInt();

        switch(choice){

            case 1:
                book b = new book();
                ob.addBook(b);
                break;

            case 2:
                ob.upgradeBookQty();
                break;

            case 3:
                System.out.println("Enter 1 to Search with Serial No.");
                System.out.println("Enter 2 to Search with Author Name(Full Name).");
                searchChoice = input.nextInt();

                switch(searchChoice){

                    case 1:
                        ob.searchBySno();
                        break;
                    case 2:
                        ob.searchByAuthorName();

                }
                break;

            case 4:
                ob.showAllBooks();
                break;
            case 5:
                student s = new student();
                obStudent.addStudent(s);
                break;
            case 6:
                obStudent.showAllStudents();
                break;
            case 7:
                obStudent.checkOutBook(ob);
                break;
            case 8:
                obStudent.checkInBook(ob);
                break;
            default:
                System.out.println("CHOICE SHOULD BE BETWEEN 0 TO 8.");

        }

    }
    while (choice!=0);
































}

}