用Java编程定义一个Book类可以从键盘输入书名和价格并能根据价格进行比较。创建一个泛型集合存放图书,对图书进行排序并输出。
时间: 2024-03-10 17:45:14 浏览: 87
好的,以下是Java代码实现:
```
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class Book implements Comparable<Book> {
private String title;
private double price;
public Book(String title, double price) {
this.title = title;
this.price = price;
}
public String getTitle() {
return title;
}
public double getPrice() {
return price;
}
public void setTitle(String title) {
this.title = title;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public int compareTo(Book book) {
if (this.price > book.price) {
return 1;
} else if (this.price < book.price) {
return -1;
} else {
return 0;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Book> books = new ArrayList<>();
System.out.println("Please enter the number of books: ");
int num = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < num; i++) {
System.out.println("Please enter the title of book " + (i + 1) + ": ");
String title = scanner.nextLine();
System.out.println("Please enter the price of book " + (i + 1) + ": ");
double price = scanner.nextDouble();
scanner.nextLine();
books.add(new Book(title, price));
}
Collections.sort(books);
System.out.println("Sorted by price (ascending order):");
for (Book book : books) {
System.out.println(book.getTitle() + " - $" + book.getPrice());
}
Collections.sort(books, new Comparator<Book>() {
@Override
public int compare(Book book1, Book book2) {
return book2.getTitle().compareTo(book1.getTitle());
}
});
System.out.println("\nSorted by title (descending order):");
for (Book book : books) {
System.out.println(book.getTitle() + " - $" + book.getPrice());
}
}
}
```
在这个例子中,我们首先在`main`方法中使用`Scanner`从键盘输入要创建的书籍数量,并使用循环逐个输入每个书籍的标题和价格。然后,我们将每个`Book`对象添加到`ArrayList`中。
接下来,我们使用`Collections.sort`方法对图书进行排序。在第一次排序中,我们使用默认的价格比较方法来对图书进行排序(升序)。在第二次排序中,我们使用自定义的标题比较方法对图书进行排序(降序)。最后,我们打印出每个图书的标题和价格来验证排序是否正确。
阅读全文