现有Book类,有属性成员,请定义成员的方法和构造方法,请编程实现使得书籍按价格降序输出
时间: 2023-08-22 20:07:10 浏览: 81
以下是一个简单的Book类的实现,包括成员变量和方法,以及构造方法。要按价格降序输出,我们可以使用Java中的Collections.sort()方法,并传入一个Comparator对象,以比较价格大小。
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Book {
private String title;
private String author;
private double price;
public Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public double getPrice() {
return price;
}
public static void main(String[] args) {
ArrayList<Book> books = new ArrayList<>();
books.add(new Book("Java Programming", "John Smith", 29.99));
books.add(new Book("Python Programming", "Jane Doe", 24.99));
books.add(new Book("Data Structures", "Bob Johnson", 34.99));
// Sort by price in descending order
Collections.sort(books, new Comparator<Book>() {
@Override
public int compare(Book b1, Book b2) {
return Double.compare(b2.getPrice(), b1.getPrice());
}
});
// Print sorted books
for (Book book : books) {
System.out.println(book.getTitle() + " by " + book.getAuthor() + " - $" + book.getPrice());
}
}
}
```
输出结果:
```
Data Structures by Bob Johnson - $34.99
Java Programming by John Smith - $29.99
Python Programming by Jane Doe - $24.99
```
阅读全文