请用【java】帮我写一段图书借阅代码,并帮我讲解下实现逻辑
时间: 2024-09-27 18:11:57 浏览: 38
当然,我可以帮你创建一个简单的图书借阅系统的Java代码示例。这个例子会包含一个`Book`类、一个`Library`类和一个`Borrower`类,以表示书籍、图书馆和读者。这里主要关注基本的借阅功能。
首先,我们定义一个`Book`类:
```java
public 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;
}
// getter and setter methods
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
public boolean isAvailable() { return isAvailable; }
public void setAvailable(boolean available) { isAvailable = available; }
}
```
接着,创建一个`Library`类,用于管理书籍:
```java
import java.util.ArrayList;
import java.util.List;
public class Library {
private List<Book> books;
public Library() {
this.books = new ArrayList<>();
}
public void addBook(Book book) {
books.add(book);
}
public Book borrowBook(String title) {
for (Book book : books) {
if (book.getTitle().equals(title) && book.isAvailable()) {
book.setAvailable(false);
return book;
}
}
throw new IllegalArgumentException("Book not found or already borrowed.");
}
public void returnBook(Book book) {
for (int i = 0; i < books.size(); i++) {
if (books.get(i).equals(book)) {
books.set(i, book);
book.setAvailable(true);
break;
}
}
}
}
```
最后,`Borrower`类代表读者:
```java
public class Borrower {
private String name;
public Borrower(String name) {
this.name = name;
}
public void borrowBook(Book book) {
System.out.println(name + " is borrowing " + book.getTitle());
}
public void returnBook(Book book) {
System.out.println(name + " has returned " + book.getTitle());
}
}
```
实现逻辑简述:
- `Book`类存储书的基本信息并跟踪其是否可用。
- `Library`类维护一个书籍列表,提供添加书籍、借书(如果书可借)和还书的方法。
- `Borrower`类有名字,可以借书(从图书馆)和还书(给图书馆)。
当一个读者尝试借书时,图书馆检查是否有这本书并且它是可用的。如果满足条件,书就被标记为已借出,然后返回给读者。反之,如果书不可借或找不到该书,则抛出异常。同样,归还一本书时,图书馆会在列表中找到相应的书并将其设置为可用状态。
阅读全文