java集合编写读者类实现增删改查和充值的代码
时间: 2023-12-03 10:46:47 浏览: 59
以下是一个简单的实现读者类的代码,包含增删改查和充值功能。其中,使用了Java集合类ArrayList来存储读者信息。
```java
import java.util.ArrayList;
public class Reader {
private String name;
private String id;
private double balance;
private ArrayList<Book> borrowedBooks; // 存储已借阅的图书
public Reader(String name, String id) {
this.name = name;
this.id = id;
this.balance = 0;
this.borrowedBooks = new ArrayList<>();
}
// 借书
public void borrow(Book book) {
borrowedBooks.add(book);
}
// 还书
public void returnBook(Book book) {
borrowedBooks.remove(book);
}
// 充值
public void recharge(double amount) {
this.balance += amount;
}
// 获取当前余额
public double getBalance() {
return balance;
}
// 修改读者信息
public void updateInfo(String name, String id) {
this.name = name;
this.id = id;
}
// 根据书名查询已借阅的图书
public ArrayList<Book> searchBorrowedBooks(String bookName) {
ArrayList<Book> result = new ArrayList<>();
for (Book book : borrowedBooks) {
if (book.getTitle().equals(bookName)) {
result.add(book);
}
}
return result;
}
// 根据ID查询已借阅的图书
public Book searchBorrowedBookById(String bookId) {
for (Book book : borrowedBooks) {
if (book.getId().equals(bookId)) {
return book;
}
}
return null;
}
}
```
其中,Book类表示图书类,具体实现可参考以下代码:
```java
public class Book {
private String id;
private String title;
private String author;
private double price;
public Book(String id, String title, String author, double price) {
this.id = id;
this.title = title;
this.author = author;
this.price = price;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public double getPrice() {
return price;
}
}
```
以上代码仅为示例,实际应用中可能需要根据具体需求进行修改和完善。
阅读全文