Java实现图书的借阅功能,不包含数据库
时间: 2023-05-27 18:04:32 浏览: 49
以下是一个基本的Java实现图书的借阅功能的示例代码,不包含数据库:
```java
import java.util.ArrayList;
class Book {
private String title;
private String author;
private boolean isAvailable;
public Book(String title, String author) {
this.title = title;
this.author = author;
this.isAvailable = true;
}
public String getTitle() {
return this.title;
}
public String getAuthor() {
return this.author;
}
public boolean isAvailable() {
return this.isAvailable;
}
public void borrow() {
if (this.isAvailable) {
this.isAvailable = false;
}
}
public void returnBook() {
if (!this.isAvailable) {
this.isAvailable = true;
}
}
}
class Library {
private ArrayList<Book> books;
public Library() {
this.books = new ArrayList<Book>();
}
public void addBook(Book book) {
this.books.add(book);
}
public void removeBook(Book book) {
this.books.remove(book);
}
public void borrowBook(String title) {
for (Book book : this.books) {
if (book.getTitle().equals(title) && book.isAvailable()) {
book.borrow();
System.out.println("You have borrowed \"" + book.getTitle() + "\"");
return;
}
}
System.out.println("\"" + title + "\" is not available for borrowing");
}
public void returnBook(String title) {
for (Book book : this.books) {
if (book.getTitle().equals(title) && !book.isAvailable()) {
book.returnBook();
System.out.println("You have returned \"" + book.getTitle() + "\"");
return;
}
}
System.out.println("\"" + title + "\" was not borrowed from this library");
}
}
public class Main {
public static void main(String[] args) {
Book book1 = new Book("The Hobbit", "J.R.R. Tolkien");
Book book2 = new Book("Harry Potter and the Philosopher's Stone", "J.K. Rowling");
Library library = new Library();
library.addBook(book1);
library.addBook(book2);
library.borrowBook("The Hobbit");
library.borrowBook("Harry Potter and the Philosopher's Stone");
library.borrowBook("The Great Gatsby");
library.returnBook("The Great Gatsby");
library.returnBook("The Hobbit");
library.returnBook("Harry Potter and the Philosopher's Stone");
}
}
```
以上示例实现了一个简单的借阅系统,包括 `Book` 和 `Library` 两个类。 `Book` 类表示一本书,包含书名、作者和可用状态,并提供了借阅和归还的方法。 `Library` 类表示一个图书馆,包含了可以借阅的书籍列表,并提供了添加、删除、借阅和归还书籍的方法。 `Main` 类是入口点,用于测试借阅系统的功能。