【发布时间】:2018-04-04 21:48:43
【问题描述】:
我需要创建一个列表书籍和地图奖励。我的目标是浏览列表并查看
The book “<book name>” by <book author> which sold <times published> copies,
received <award for this book> award
如果书单作者等于map Shakespeare == Shakespeare then output
The book "Romeo and Juliet" by Shakespeare which sold 4500 copies,
received Too much drama award.
否则
The book "Romeo and Juliet" by Shakespeare which sold 4500 copies,
received no award
我是 Java 新手,我的问题是如何在循环和比较列表时向 toString 发送新的奖励参数
我的书课
public class Book implements Comparable<Book> {
private String author;
private String name;
private int timesPublished;
public Book(String author, String name, int timesPublished) {
this.author = author;
this.name = name;
this.timesPublished = timesPublished;
}
public int getTimesPublished() {
return timesPublished;
}
public String getName() {
return name;
}
//@Override
public int compareTo(Book compareBook) {
if (this.getTimesPublished() == compareBook.getTimesPublished()) {
return this.getName().toLowerCase().compareTo(compareBook.getName().toLowerCase());
} else {
return this.getTimesPublished() - compareBook.getTimesPublished();
}
}
//@Override
public String toString() {
return String.format("The book \"%s\" by %s which sold %s copies", name, author, timesPublished);
}
}
我的主要
public static void main(String[] args) {
Map<String, String> awards = new HashMap<String, String>();
awards.put("Shakespeare", "Too much drama");
awards.put("Swift", "Survival guide");
awards.put("Austen", "Did not read");
awards.put("Dumas", "Sweet revenge");
List<Book> list = new LinkedList<Book>();
list.add(new Book("Dumas", "The Count of Monte Cristo", 1245));
list.add(new Book("Shakespeare", "Romeo and Juliet", 4500));
list.add(new Book("Austen", "Pride", 1000));
list.add(new Book("Swift", "Aulliver", 1000));
list.add(new Book("Tolstoy", "Best", 1000));
Collections.sort(list);
for(Book temp: list) {
System.out.println(temp);
}
}
【问题讨论】:
-
您不能将参数传递给
toString()。您需要将奖项作为Book对象的一部分(从对象模型的角度来看这没有意义),或者与课程之外的奖项结合使用。 -
@RAZ_Muh_Taz OP 将奖项与作者联系起来,而不是书籍本身。
标签: java list dictionary tostring