【问题标题】:Traverse Sorting in alphabetical order, print one by one and number of unique books按字母顺序遍历排序,一一打印唯一书籍的数量
【发布时间】:2015-11-24 15:30:54
【问题描述】:

我的第一堂课:

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对象返回作者的书籍列表,一一遍历书籍列表并列出唯一书籍的数量

希望你能帮帮我

【问题讨论】:

    标签: java sorting arraylist


    【解决方案1】:

    尝试使用 Collections 类中的 sort 方法,例如:

    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()) {
        ....
    }
    

    【讨论】:

    • 我要把它放在书架课上,因为我需要把它放在那个课上的书架上吗?或者你有更简单的代码告诉我,以便我更好地理解?
    猜你喜欢
    • 2021-06-24
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多