-2

i have created a class with various attributes. now in output i want the arrays of object displayed in ascending order of book price. Moreover in output i am getting value in some different format. what is the correct logic. how do rectify the output format. i am attaching my code along with inputs given and output.[![attributes are of 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]);}
        }


    }

}}

enter image description here1 https://i.stack.imgur.com/3hU18.png

A_B
  • 29
  • 1
  • 8
  • A picture of your code is not your code. Please read [Why not upload images of code on SO when asking a question?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question) – azurefrog Jan 29 '20 at 20:17
  • In addition to including your code as text, please also include the actual text of your error message. If the error message includes a line number, indicate in your code (via a comment) which line is the one referenced by the error message. – Jordan Jan 29 '20 at 20:18
  • @Jordan, i am not getting any error. but output is showing some random text. and i am not sure if my logic is correct or not?! – A_B Jan 29 '20 at 20:22
  • @Aaryaa My mistake, I must have confused this with a different question I was looking at. See [this previous question](https://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4), which has the answer you're looking for. – Jordan Jan 29 '20 at 20:23

2 Answers2

0

You can implement a Comparator this way (old way).

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

Then, for Arrays and Collections you use

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

Edit after your comment :

    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);
     }`

Please override the toString() method in Book class

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

I have kept this as simple and as close to your original code as possible.

0

Edit: Per your reply, the way to do this by taking user input has been written in a separate method at the bottom :)

You can implement a Comparator. You can create ones for each of the fields that you want like this:

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;
  }
}

And then you can use it like this:

    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());
    }

Output:

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

I hope that helps!

Edit: New method to take user input of 4 Book Objects per your question(this assumes they input the correct input, I'll let you handle the exceptions possibilities):

  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;
  }
djharten
  • 374
  • 1
  • 12
  • how do i use this method when i have to take input from user? i have to take user input of 4 arrays of object. – A_B Jan 30 '20 at 13:45
  • Updated my first post with a new method at the bottom that can do this for you :) – djharten Jan 30 '20 at 14:13