top of page
Java Arrays - Hands on 2
Problem 2:
Create class Book with below attributes:
id - int
title - String
author - String
price - double
Write getters, setters and parameterized constructor as required.
Create class Solution with main method.
Implement static method - searchTitle in Solution class.
This method will take a parameter of String value along with other parameter as array of Book objects.
It will return array of books where String value parameter appears in the title attribute (with case insensitive search).
This method should be called from main method and display id of returned objects in ascending order.
Before calling this method, use Scanner object to read values for four Book objects referring attributes in the above sequence.
Next, read the value search parameter.
Next call the method and display the result.
Consider below sample input and output:
Input:
1
hello world
aaa writer
50
2
World cup
bbb writer
55
3
Planet earth
ccc writer
45
4
India's history
ddd writer
40
WORLD
Output:
1
2
​
Solutions:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.*;
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[] res=new Book[4];
for(int i=0;i<booksArray.length;i++)
{
booksArray[i]=new Book();
res[i]=new Book();
}
for(int i = 0;i<4;i++)
{
booksArray[i].id = scn.nextInt();scn.nextLine();
booksArray[i].title = scn.nextLine();
booksArray[i].author = scn.nextLine();
booksArray[i].price = scn.nextDouble();
}
String value=scn.next();
res=searchTitle(value, booksArray);
int [] matchedId=new int[4];
int j=0;
for(int i=0;i<res.length;i++)
{
if(res[i].id!=0)
{
matchedId[j++]=res[i].id;
}
}
Arrays.sort(matchedId);
for(int i=0;i<matchedId.length;i++)
{
if(matchedId[i]!=0)
System.out.println(matchedId[i]);
}
}
public static Book[] searchTitle(String value, Book[] books)
{
int k=0;
Book[] matching=new Book[4];
for(int i=0;i<matching.length;i++)
matching[i]=new Book();
for(int i=0;i<books.length;i++)
{
String val=value.toLowerCase();
String bookTitle=books[i].title.toLowerCase();
if(bookTitle.contains(val))
{
matching[k++]=books[i];
}
}
return matching;
}
}
class Book
{
int id;
String title;
String author;
double price;
public int getId()
{
return this.id;
}
public void setId(int id)
{
this.id=id;
}
public String getTitle()
{
return this.title;
}
public void setTitle(String title)
{
this.title=title;
}
public String getAuthor()
{
return this.author;
}
public void setAuthor(String author)
{
this.author=author;
}
public double getPrice()
{
return this.price;
}
public void setPrice(double price)
{
this.price=price;
}
}
Java p2 Arrays - Hands on copy: About
bottom of page