views:

53

answers:

5

I have a program which needs to be able to search through an ArrayList of 'book' objects, and decide which ones meet given criteria.

You can search by Name, ID Number, or Year published. Or just by any assortment of the above.

Currently i use nested if statements, where a null value means that field wasn't specified and to display all.

for(int x = 0; x<bookList.size(); x++)
{
    if(bookList.get(x).callNum.equals(callNum) || callNum == null)
    {
         if(bookList.get(x).title.equals(title) || title == null)
         {
             if((bookList.get(x).year>= startDate 
                 && bookList.get(x).year <= endDate) || timeFrame == null)
             {
                 bookList.get(x).ToString();
             }
         }
     }
 }

The only place i have a problem, is that for the title variable. I need it to do word-level matching. So if a book is called 'Java Programming' and another is called 'Object Oriented Programming in Java', both should be returned when the search is looking for 'Java'. How can i accomplish this?

I appreciate any help, thanks for you time!

A: 

String.indexOf() is the easy way.

String s1 = "a b c";
s1.indexOf("b")

will return 2 (I think). If you were try with "x", it would return -1, because it was not found. Check the API at http://download.oracle.com/javase/6/docs/api/java/lang/String.html#indexOf(java.lang.String)

regex might be the better way.

As a note, 4 levels of nesting is confusing and should be avoided if possible.

hvgotcodes
A: 

First of all, extract bookList.get(x) expression into a local variable, so you won't have to repeat it multiple times in your conditions.

You can use matching sub-string using name.indexOf("Java")>-1 or name.contains("Java")

Eugene Kuleshov
+2  A: 

How about:

if (title == null || bookList.get(x).title.contains(title))

assuming bookList.get(x).title is a String.

Chris Knight
+1 `contains` is really the right thing to use here.
Mark E
A: 

Use String.contains(pattern) method in your condition : eg. booktitle.contains("Java");

Ramp
A: 

String.indexOf(..) will work. I would assume you will probably also want to toLowerCase() book names and the criteria. Additionally do you care about the order? By that I mean should a search for "Java Programming" should match both titles above even though in the 2nd the words are in the other order and "in" is between them? If so you will want to split("\s+") and look for each word individually.

Plaudit Design - Web Design