写一个使用类,测试接口中的所有方法,方法如下void addBook(Book b); //添加图书 void deleteByIsbn(String ibsn); // void deleteByAuthor(String author); // void updateBook(Book b); //附加题 int size(); //统计书的数量 void clear(); //清空所有图书 Book selectByIsbn(String isbn); Book[] getAllBooks(); //获取所有图书
时间: 2023-05-27 10:02:17 浏览: 139
Java开发社区图书馆和书店售卖信息系统小游戏代码.docx
```
public class Library {
private List<Book> books;
public Library() {
this.books = new ArrayList<>();
}
public void addBook(Book b) {
books.add(b);
System.out.println("成功添加一本书:" + b.getTitle());
}
public void deleteByIsbn(String isbn) {
for (Book b : books) {
if (b.getIsbn().equals(isbn)) {
books.remove(b);
System.out.println("成功删除一本书:" + b.getTitle());
return;
}
}
System.out.println("找不到该ISBN号对应的书籍");
}
public void deleteByAuthor(String author) {
int count = 0;
Iterator<Book> it = books.iterator();
while (it.hasNext()) {
Book b = it.next();
if (b.getAuthor().equals(author)) {
it.remove();
count++;
}
}
if (count == 0) {
System.out.println("找不到该作者对应的书籍");
} else {
System.out.println("成功删除" + count + "本书");
}
}
public void updateBook(Book b) {
for (int i = 0; i < books.size(); i++) {
if (books.get(i).getIsbn().equals(b.getIsbn())) {
books.set(i, b);
System.out.println("成功更新一本书:" + b.getTitle());
return;
}
}
System.out.println("找不到该ISBN号对应的书籍");
}
public int size() {
return books.size();
}
public void clear() {
books.clear();
System.out.println("已清空所有图书");
}
public Book selectByIsbn(String isbn) {
for (Book b : books) {
if (b.getIsbn().equals(isbn)) {
return b;
}
}
System.out.println("找不到该ISBN号对应的书籍");
return null;
}
public Book[] getAllBooks() {
return books.toArray(new Book[books.size()]);
}
public static void main(String[] args) {
Library library = new Library();
// 添加图书
Book b1 = new Book("9787121332379", "Java编程思想", "Bruce Eckel");
Book b2 = new Book("9787111128069", "Java核心技术", "Cay S. Horstmann, Gary Cornell");
Book b3 = new Book("9787508353937", "八分钟演讲", "许倩");
library.addBook(b1);
library.addBook(b2);
library.addBook(b3);
// 获取所有图书
Book[] allBooks = library.getAllBooks();
for (Book b : allBooks) {
System.out.println(b.getTitle());
}
// 更新图书信息
b2.setAuthor("Cay S. Horstmann, Gary Cornell, Alvin Alexander");
library.updateBook(b2);
// 删除图书(ISBN号)
library.deleteByIsbn("1234567890");
library.deleteByIsbn("9787121332379");
// 删除图书(作者)
library.deleteByAuthor("abc");
library.deleteByAuthor("Cay S. Horstmann, Gary Cornell, Alvin Alexander");
// 清空所有图书
library.clear();
// 统计书的数量
System.out.println("图书馆共有" + library.size() + "本书");
// 查询图书(ISBN号)
Book b4 = library.selectByIsbn("1234567890");
if (b4 != null) {
System.out.println("《" + b4.getTitle() + "》的作者是" + b4.getAuthor());
}
// 查询图书(不存在的ISBN号)
library.selectByIsbn("1111111111");
}
}
```
阅读全文