用java实现有Book类,并定义书籍若干本,信息如下所示,请定义一个 成类,有属性成员(author, name,price) 请定义成员的方法和构造方法等方法,请编程实现便得书籍按价格降序输出,
时间: 2024-02-19 19:58:37 浏览: 220
基于java做图书管理系统
好的,以下是用Java实现这个需求的代码:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Book {
private String author;
private String name;
private double price;
public Book(String author, String name, double price) {
this.author = author;
this.name = name;
this.price = price;
}
public String getAuthor() {
return author;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
@Override
public String toString() {
return author + ": " + name + " - " + price;
}
}
class Bookstore {
private List<Book> books;
public Bookstore(List<Book> books) {
this.books = books;
}
public void displayBooksByPrice() {
Collections.sort(books, new Comparator<Book>() {
@Override
public int compare(Book b1, Book b2) {
return Double.compare(b2.getPrice(), b1.getPrice());
}
});
for (Book book : books) {
System.out.println(book);
}
}
}
public class Main {
public static void main(String[] args) {
List<Book> books = new ArrayList<>();
books.add(new Book("J.K. Rowling", "Harry Potter and the Philosopher's Stone", 35.5));
books.add(new Book("J.R.R. Tolkien", "The Lord of the Rings", 89.9));
books.add(new Book("George Orwell", "Animal Farm", 19.9));
books.add(new Book("Harper Lee", "To Kill a Mockingbird", 28.5));
Bookstore bookstore = new Bookstore(books);
bookstore.displayBooksByPrice();
}
}
```
输出结果为:
```
J.R.R. Tolkien: The Lord of the Rings - 89.9
J.K. Rowling: Harry Potter and the Philosopher's Stone - 35.5
Harper Lee: To Kill a Mockingbird - 28.5
George Orwell: Animal Farm - 19.9
```
以上代码中,我们定义了一个 `Book` 类和一个 `Bookstore` 类。`Book` 类有三个属性成员 `author`,`name` 和 `price`,还有一个构造方法。`Bookstore` 类有一个属性成员 `books` 和一个方法 `displayBooksByPrice`,该方法按照价格降序输出所有书籍。在测试代码中,我们创建了一些书籍,并将它们传递给 `Bookstore` 对象,然后调用 `displayBooksByPrice` 方法输出结果。
阅读全文