我的第一堂课:
public class Book
{
private int id;
private String author, title;
public Book(int id, String author, String title)
{
this.id = id;
this.author = author;
this.title = title;
}
public int getId()
{
return id;
}
public String getAuthor()
{
return author;
}
public String getTitle()
{
return title;
}
public void setId(int setID)
{
this.id = setID;
}
public void setAuthor(String setAuthor)
{
this.author = setAuthor;
}
public void setTitle(String setTitle)
{
this.author = setTitle;
}
public String toString()
{
String info = "\tID: " + id + "\tAuthor: " + author + "\tTitle: " + title +"\n";
return info;
}
}
我的第二堂课:
public class BookShelf
{
private Book books;
ArrayList<Book> listOfBooks = new ArrayList<Book>();
public void addBook(Book addBook)
{
listOfBooks.add(addBook);
}
public ArrayList<Book> returnListOfBooks()
{
return listOfBooks;
}
public ArrayList<Book> returnListOfBooksByAuthor(String requestAuthor)
{
String author = books.getAuthor();
ArrayList<Book> authorList = new ArrayList<>();
for (Book b: listOfBooks)
{
if(author.equals(requestAuthor))
{
authorList.add(b);
}
}
return authorList;
}
}
我的熟练班:
import java.util.ArrayList;
import java.util.Scanner;
public class BookShelfApp
{
public static void main(String[] args)
{
ArrayList<Book> book = new ArrayList<>();
BookShelf shelf = new BookShelf();
Scanner Id = new Scanner(System.in);
Scanner Author = new Scanner(System.in);
Scanner Title = new Scanner(System.in);
for(int i=0;i<3;i++)
{
System.out.print("Enter the ID of book:");
int id = Id.nextInt();
System.out.print("Enter the author of book:");
String author = Author.nextLine();
System.out.print("Enter the title of book:");
String title = Title.nextLine();
Book books = new Book(id, author, title);
shelf.addBook(books);
}
System.out.println(shelf.listOfBooks);
}
}
我设法调用方法从书架中返回书籍列表。我不知道如何遍历数组并按字母顺序按标题排序打印出来
最后,调用方法从BookShelf对象返回作者的书籍列表,逐个遍历书籍列表并列出唯一书籍的数量
希望你能帮帮我
答案 0 :(得分:0)
尝试使用sort
类中的Collections
方法,例如:
Collections.sort(shelf.returnListOfBooks(), new Comparator<Book>() {
public int compare(Book thisBook, Book thatBook) {
return String.compareTo(thisBook.getTitle(), thatBook.getTitle());
}
});
要遍历列表,您需要一个for循环,如:
for (Book book : shelf.returnListOfBooks()) {
....
}