【发布时间】:2016-01-11 13:42:12
【问题描述】:
我在 BookShelf 类中有一个单独的方法 returnListOfBooks,它按字母顺序按标题排序
private ArrayList<Book> listOfBooks;
public BookShelf(ArrayList<Book> listOfBooks) {
this.listOfBooks = listOfBooks;
}
public void addBook(Book a) {
listOfBooks.add(a);
}
public ArrayList<Book> returnListOfBooks() {
for (int i = listOfBooks.size() - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
//Is the two elements out of order?
if (listOfBooks.get(j).getTitle().compareTo(
listOfBooks.get(j + 1).getTitle()) < 0)
{
//yes, then swap
Book temp = listOfBooks.get(j);
listOfBooks.set(j, listOfBooks.get(j + 1));
listOfBooks.set(j + 1, temp);
} // end of inner for loop - arranging
}
}
for (int t = 0; t<listOfBooks.size(); t++)
{
System.out.print(listOfBooks.get(t) + " ");
}
System.out.println();
return listOfBooks;
}
用户必须在书架中输入 20 本书,一旦已经有 20 本书,我必须在主驱动程序中调用此方法并遍历书籍列表并按标题按字母顺序逐一打印命令。但是,当我这样做时,只打印出排序列表中的第一本书详细信息。
这是我在主驱动程序中调用该方法的方式:
ArrayList<Book> listOfBooks = myBookshelf.returnListOfBooks();
for (Book b: listOfBooks){
System.out.println(b);
}
有人知道我哪里出错了吗?希望你能帮帮我。
样本输入:
输入图书ID:23456输入本书作者:J.K罗琳
输入书名:哈利波特与火焰杯
输入图书ID:56780
请输入本书的作者:约翰·格林
输入书名:我们开始时的错误
输入图书ID:45678
请输入本书的作者:James Patterson
输入书名:动物园
....
(用户将输入 20 次)
预期输出:
ID:23456,作者:J.K Rowling,标题:哈利波特与高脚杯 火
ID:56780,作者:John Green,标题:我们开始时的错误
ID:45678,作者:James Patterson,标题:Zoo
...
(依此类推,按标题按字母顺序排列)
我得到的输出:
Enter ID of the book: 23456
Enter the author of the book: J.K Rowling
Enter title of the book: Harry Potter and the Goblet of Fire
Enter ID of the book: 56780
Enter the author of the book: John Green
Enter title of the book: The Fault in Our Starts
Enter ID of the book: 45678
Enter the author of the book: James Patterson
Enter title of the book: Zoo
....
(输入20次)
ID: 23456, Author: J.K Rowling, Title: Harry Potter and the Goblet of Fire
BUILD SUCCESSFUL (total time: 16 seconds)
【问题讨论】:
-
你没有展示
listOfBooks是如何初始化的(你也没有在几个小时前发布的同一个问题中展示这一点)。 -
看起来只有一本书最终出现在数组中。你是怎么看书的?你使用 add() 吗?还是 set()?
-
请将系统添加出:public ArrayList
returnListOfBooks() { System.output.println(listOfBooks); -
@Eran 请原谅。添加在
-
@Arkadiy 使用过
add()