用Java编写一个book类,有属性成员(author,name,price),请定义成员的方法和构造方法等方法,请编程实现使得书籍按价格9降序输出
时间: 2024-02-16 15:05:16 浏览: 132
好的,下面是一个简单的Book类的Java代码:
```java
import java.util.*;
public class Book implements Comparable<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 String.format("%s, %s, %.2f", author, name, price);
}
@Override
public int compareTo(Book o) {
return Double.compare(o.price, this.price); // 价格降序排序
}
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", 28.50));
books.add(new Book("Harper Lee", "To Kill a Mockingbird", 19.99));
books.add(new Book("George Orwell", "1984", 15.50));
books.add(new Book("J.R.R. Tolkien", "The Lord of the Rings", 39.95));
books.add(new Book("Jane Austen", "Pride and Prejudice", 12.99));
Collections.sort(books); // 按价格降序排序
for (Book book : books) {
System.out.println(book);
}
}
}
```
以上代码中,我们定义了一个`Book`类,包含三个属性成员`author`(作者)、`name`(书名)、`price`(价格),以及一个构造方法和三个获取属性的方法。此外,我们还实现了`Comparable`接口,重写了`compareTo`方法,用于按价格降序排序。最后,在`main`方法中创建了一个包含五本书的列表,并使用`Collections.sort()`方法按价格降序排序,然后遍历列表输出每本书的信息。
阅读全文