通过java基础写一个图书馆管理系统
时间: 2023-12-14 07:40:14 浏览: 109
好的,下面是一个简单的图书馆管理系统的Java代码:
```
import java.util.*;
class Book {
private String title;
private String author;
private int numCopies;
public Book(String title, String author, int numCopies) {
this.title = title;
this.author = author;
this.numCopies = numCopies;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public int getNumCopies() {
return numCopies;
}
public void setNumCopies(int numCopies) {
this.numCopies = numCopies;
}
public void display() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Number of Copies: " + numCopies);
}
}
class Library {
private String name;
private ArrayList<Book> books = new ArrayList<Book>();
public Library(String name) {
this.name = name;
}
public void addBook(Book book) {
books.add(book);
}
public void displayBooks() {
for (Book book : books) {
book.display();
}
}
public void borrowBook(String title) {
for (Book book : books) {
if (book.getTitle().equals(title)) {
if (book.getNumCopies() > 0) {
book.setNumCopies(book.getNumCopies() - 1);
System.out.println("You have borrowed the book " + title + ".");
} else {
System.out.println("Sorry, all copies of the book " + title + " are currently checked out.");
}
return;
}
}
System.out.println("Sorry, the book " + title + " is not available in this library.");
}
public void returnBook(String title) {
for (Book book : books) {
if (book.getTitle().equals(title)) {
book.setNumCopies(book.getNumCopies() + 1);
System.out.println("You have returned the book " + title + ".");
return;
}
}
System.out.println("Sorry, the book " + title + " is not part of this library's collection.");
}
}
public class LibrarySystem {
public static void main(String[] args) {
Library library = new Library("My Library");
Book book1 = new Book("The Catcher in the Rye", "J.D. Salinger", 3);
Book book2 = new Book("To Kill a Mockingbird", "Harper Lee", 2);
Book book3 = new Book("1984", "George Orwell", 5);
library.addBook(book1);
library.addBook(book2);
library.addBook(book3);
System.out.println("Welcome to " + library.name + ".");
System.out.println("Here are the available books:");
library.displayBooks();
library.borrowBook("1984");
library.borrowBook("1984");
library.borrowBook("1984");
library.borrowBook("Animal Farm");
library.returnBook("1984");
library.returnBook("1984");
library.returnBook("1984");
System.out.println("Here are the available books:");
library.displayBooks();
}
}
```
这个代码实现了一个简单的图书馆管理系统。`Book`类表示一本书,包括书名、作者和副本数。`Library`类表示整个图书馆,包括图书馆名称和书籍列表。它包括了添加书籍、展示书籍、借出书籍和归还书籍等方法。`LibrarySystem`类是程序的入口,它创建了一个图书馆实例并添加了一些书籍,然后展示了所有可用的书籍,并模拟了借书和还书的过程。
阅读全文