我需要创建一个List书籍和地图奖励。我的目标是通过列表并查看
The book “<book name>” by <book author> which sold <times published> copies,
received <award for this book> award
如果图书清单作者等于地图莎士比亚==莎士比亚然后输出
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);
}
}
答案 0 :(得分:1)
为book类中的author变量创建一个getter。你需要这个方法,因为变量是私有的,并且在类之外是不可访问的,除非你为变量创建一个getter,如此
public String getAuthorName()
{
return author;
}
然后,当您打印输出时,您可以执行以下操作来检查地图中的作者,如果you get back null您知道奖励不存在,否则您将获得奖励中的内容图
for(Book temp: list) {
String awardName = awards.get(temp.getAuthorName());//use the getter to see what the current book's author is
System.out.println(temp + " received " + (awardName == null ? "no" : awardName) + " award");
}