如何用java开发一个藏书系统,有添加作者、书名、价格、出版社、出版年份,方法有添加藏书、根据作者查找图书、根据书名查找图书、计算藏书总数、计算藏书总金额
时间: 2023-10-20 12:20:42 浏览: 126
基于java做图书管理系统
您好!关于您的问题,我可以回答。首先,您可以创建一个“Book”类,该类应该具有“作者”、“书名”、“价格”、“出版社”和“出版年份”这些属性。然后,您可以创建一个“Library”类,它将管理所有的“Book”对象。该类可以包括以下方法:添加藏书、根据作者查找图书、根据书名查找图书、计算藏书总数和计算藏书总金额。
在添加藏书的方法中,您可以创建一个新的“Book”对象,并将其添加到“Library”对象中。在查找图书的方法中,您可以遍历“Library”对象中所有的“Book”对象,并返回符合要求的书籍。在计算藏书总数和总金额的方法中,您可以遍历“Library”对象中所有的“Book”对象,并计算总数和总金额。
这里提供一个简单的基于Java的“Library”类的代码示例:
```java
public class Book {
private String author;
private String title;
private double price;
private String publisher;
private int year;
public Book(String author, String title, double price, String publisher, int year) {
this.author = author;
this.title = title;
this.price = price;
this.publisher = publisher;
this.year = year;
}
// getters and setters omitted for brevity
}
import java.util.ArrayList;
import java.util.List;
public class Library {
private List<Book> books = new ArrayList<>();
public void addBook(Book book) {
books.add(book);
}
public List<Book> findBooksByAuthor(String author) {
List<Book> result = new ArrayList<>();
for (Book book : books) {
if (book.getAuthor().equals(author)) {
result.add(book);
}
}
return result;
}
public List<Book> findBooksByTitle(String title) {
List<Book> result = new ArrayList<>();
for (Book book : books) {
if (book.getTitle().equals(title)) {
result.add(book);
}
}
return result;
}
public int getTotalBooks() {
return books.size();
}
public double getTotalAmount() {
double amount = 0;
for (Book book : books) {
amount += book.getPrice();
}
return amount;
}
}
// 使用方法示例
Library library = new Library();
Book book1 = new Book("George Orwell", "1984", 9.99, "Secker and Warburg", 1949);
Book book2 = new Book("George Orwell", "Animal Farm", 6.99, "Secker and Warburg", 1945);
library.addBook(book1);
library.addBook(book2);
System.out.println("Total books: " + library.getTotalBooks()); // 输出:Total books: 2
System.out.println("Total amount: " + library.getTotalAmount()); // 输出:Total amount: 16.98
List<Book> booksByAuthor = library.findBooksByAuthor("George Orwell");
System.out.println("Books by George Orwell: " + booksByAuthor); // 输出:Books by George Orwell: [Book [author=George Orwell, title=1984, price=9.99, publisher=Secker and Warburg, year=1949], Book [author=George Orwell, title=Animal Farm, price=6.99, publisher=Secker and Warburg, year=1945]]
```
希望本回答能够帮助您!
阅读全文