top of page
Java Arrays - Hands on 1
Problem 2:
​
Sort Books by Price
Create class Book with below attributes:
id - int
title - String
author - String
price - double
Write getters, setters and parameterized constructor.
Create class Solution with main method.
Implement static method - sortBooksByPrice in Solution class.
This method will take a parameter as array of Book objects.
It will return array of books which is sorted in ascending order of book price. Assume that no two books will have same price.
This method should be called from main method and display values of returned objects as shared in the sample.
Before calling this method, use Scanner object to read values for four Book objects referring attributes in the above sequence.
Next call the method and display the result.
Consider below sample input and output:
Input:
1
hello
writer1
50
2
cup
writer2
55
3
Planet
writer3
45
4
India
writer4
40
​
Solutions:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner scn=new Scanner(System.in);
Book[] booksArray=new Book[4];
Book[] sorted=new Book[4];
for(int i=0;i<booksArray.length;i++)
{
booksArray[i]=new Book();
sorted[i]=new Book();
}
for(int i=0;i<booksArray.length;i++)
{
booksArray[i].id=scn.nextInt();
booksArray[i].title=scn.next();
booksArray[i].author=scn.next();
booksArray[i].price=scn.nextDouble();
}
sorted=sortBooksByPrice(booksArray);
for(int i=0;i<sorted.length;i++)
{
System.out.println(sorted[i].id+" "+sorted[i].title+" "+sorted[i].author+"
"+sorted[i].price);
}
}
public static Book[] sortBooksByPrice(Book[]booksArray){
int n=booksArray.length;
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(booksArray[j].price>booksArray[j+1].price)
{
Book temp=booksArray[j];
booksArray[j]=booksArray[j+1];
booksArray[j+1]=temp;
}
}
}
return booksArray;
}
}
class Book
{
int id;
String title,author;
double price;
}
Java Arrays - Hands on 2: About
bottom of page