【问题标题】:how do i sort the array according to one of the attribute of the class? [duplicate]如何根据类的属性之一对数组进行排序? [复制]
【发布时间】:2020-05-15 09:55:15
【问题描述】:

我创建了一个具有各种属性的类。现在在输出中,我希望按书价升序显示对象数组。此外,在输出中,我以某种不同的格式获得价值。什么是正确的逻辑。如何纠正输出格式。我附上我的代码以及给定的输入和输出。[![属性是 id、title、author、price

import java.util.Scanner;

class Book{
    int id;
    String title;
    String author;
    Double price;
}



public class booksort {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        Book b1 = new Book();
        Book b2 = new Book();
        Book b3 = new Book();
        Book b4 = new Book();
        Book b[] = {b1,b2,b3,b4};
        Book temp ;
        for(int i=0;i<b.length;i++) {
            b[i].id=sc.nextInt();
            b[i].title=sc.next();
            b[i].author=sc.next();
            b[i].price=sc.nextDouble();
        }
        for(int i=0;i<b.length;i++) {
            for(int j=0;j<b.length;j++) {
                if(b[i].price>b[j].price) {
                    System.out.println(b[i]);}
        }


    }

}}

1https://i.stack.imgur.com/3hU18.png

【问题讨论】:

  • 您的代码图片不是您的代码。请阅读Why not upload images of code on SO when asking a question?
  • 除了将您的代码作为文本包括在内,还请包括您的错误消息的实际文本。如果错误消息包含行号,请在代码中(通过注释)指出错误消息引用的行。
  • @Jordan,我没有收到任何错误。但输出显示一些随机文本。我不确定我的逻辑是否正确?!
  • @Aaryaa 我的错误,我一定是把它和我正在看的另一个问题混淆了。请参阅this previous question,那里有您正在寻找的答案。

标签: java arrays class sorting attributes


【解决方案1】:

编辑:根据您的回复,通过获取用户输入来执行此操作的方法已在底部的单独方法中编写:)

您可以实现一个比较器。您可以像这样为您想要的每个字段创建一个:

public class Book {

  int id;
  String title;
  String author;
  Double price;

  public Book(int id, String title, String author, Double price) {
    super();
    this.id = id;
    this.title = title;
    this.author = author;
    this.price = price;
  }
  // getters and setters here
}

class CompareByID implements Comparator<Book> {
  public int compare(Book one, Book two) {
    return one.id - two.id;
  }
}

class CompareByTitle implements Comparator<Book> {
  public int compare(Book one, Book two) {
    return one.title.compareTo(two.title);
  }
}

class CompareByAuthor implements Comparator<Book> {
  public int compare(Book one, Book two) {
    return one.author.compareTo(two.author);
  }
}

class CompareByPrice implements Comparator<Book> {
  public int compare(Book one, Book two) {
    if(one.price < two.price)
      return -1;
    if(two.price < one.price)
      return 1;
    return 0;
  }
}

然后你可以像这样使用它:

    Book bookOne = new Book(1, "Harry Potter and the Comparator Operator", "Java Rowling", 19.99);
    Book bookTwo = new Book(2, "Answering StackOverflow instead of doing your job at work", "Djharten", 0.01);

    ArrayList<Book> bookList = new ArrayList<>();
    bookList.add(bookOne);
    bookList.add(bookTwo);

    Collections.sort(bookList, new CompareByID());
    for(Book b : bookList) {
      System.out.println(b.getId());
    }

    Collections.sort(bookList, new CompareByAuthor());
    for(Book b : bookList) {
      System.out.println(b.getAuthor());
    }

    Collections.sort(bookList, new CompareByTitle());
    for(Book b : bookList) {
      System.out.println(b.getTitle());
    }

    Collections.sort(bookList, new CompareByPrice());
    for(Book b : bookList) {
      System.out.println(b.getPrice());
    }

输出:

1
2
Djharten
Java Rowling
Answering StackOverflow instead of doing your job at work
Harry Potter and the Comparator Operator
0.01
19.99

希望对你有帮助!

编辑:根据您的问题采用 4 个图书对象的用户输入的新方法(假设他们输入了正确的输入,我会让您处理异常可能性):

  public static List<Book> createBookList() {
    List<Book> bookList = new ArrayList<>();

    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter the book information for 4 books in this format: ID Title Author Price");

    for(int i = 0; i < 4; i++) {
      int id = sc.nextInt();
      String title = sc.next();
      String author = sc.next();
      double price = sc.nextDouble();
      Book book = new Book(id, title, author, price);
      bookList.add(book);
      sc.nextLine();
    }
    return bookList;
  }

【讨论】:

  • 当我必须接受用户的输入时,如何使用此方法?我必须接受 4 个对象数组的用户输入。
  • 用底部的新方法更新了我的第一篇文章,可以为你做到这一点:)
【解决方案2】:

您可以通过这种方式(旧方式)实现比较器。

 Comparator<Book> bookPriceComparator = new Comparator<Book>() {
  public int compare(Book b1, Book b2) {
    return b1.getPrice().compareTo(b2.getPrice());
  }
 };

然后,对于您使用的数组和集合

Arrays.sort(array, bookPriceComparator);
Collections.sort(list, bookPriceComparator);

评论后编辑:

    Scanner sc = new Scanner(System.in);
    Book b1 = new Book();
    Book b2 = new Book();
    Book b3 = new Book();
    Book b4 = new Book();
    List<Book> b = new ArrayList<Book>();
    b.add(b1);
    b.add(b2);
    b.add(b3);
    b.add(b4);
    //populate the list
    for(int i=0;i<b.length;i++) {
        b.get(i).id=sc.nextInt();
        b.get(i).title=sc.next();
        b.get(i).author=sc.next();
        b.get(i).price=sc.nextDouble();
    }

    // to sort the list of books by price
    Comparator<Book> bookPriceComparator = new Comparator<Book>() {
      public int compare(Book b1, Book b2) {
        return b1.getPrice().compareTo(b2.getPrice());
      }
     };
     Collections.sort(list, bookPriceComparator);


     // print the sorted list
     for(Book book : b){
        System.out.println(book);
     }`

请重写 Book 类中的 toString() 方法

    @Override
    public String toString() {
        return "Book [id=" + this.id + ", title=" + this.title
          + ", author=" + this.author +  ", price=" + this.price +"]";
    }

我已将其保持为尽可能简单并尽可能接近您的原始代码。

【讨论】:

  • 当我必须接受用户的输入时如何使用此方法。我必须接受 4 个对象数组的用户输入。
  • 我已经编辑了答案,如果你喜欢这个答案,请点赞。
猜你喜欢
  • 2011-07-22
  • 2021-07-14
  • 2018-11-14
  • 1970-01-01
  • 2012-10-22
  • 2012-11-12
  • 2019-12-19
  • 1970-01-01
相关资源
最近更新 更多