First, in your code is - only the last book matters, you need to break if you found a suitable book, since there is no need to check the reminders (and reset the value to "no book found") after a book is found.
for(int i = 0; i < collection.size(); i++){
if(titleSearch.equalsIgnoreCase(collection.get(i).getTitle())){
titleSearch = ("\n Book Avaliable");
break; //<- added a break here, no need to go on iterating and reset titleSearch later on
}else{
titleSearch = ("\n No Books Avaliable ");
}
}
The above stills fails if your collection is empty and you search for a book (that is obviously not there).
You can solve it and improve the solution by avoiding the else
:
titleSearch = ("\n No Books Avaliable ");
for(int i = 0; i < collection.size(); i++){
if(titleSearch.equalsIgnoreCase(collection.get(i).getTitle())){
titleSearch = ("\n Book Avaliable");
break; //<- added a break here
}
}
This way you start pessimistic - the book is not there, and you "change your mind" if you later find it, and halts with this result.
The above still missing the title you are actually looking for, and that can be achieved by adding it as an argument and looking for it:
public String searchTitle(String titleSearch) {
if (titleSearch == null) return "\n No Books Avaliable ";
for(int i = 0; i < collection.size(); i++){
if(titleSearch.equalsIgnoreCase(collection.get(i).getTitle())){
return "\n Book Avaliable";
}
}
return "\n No Books Avaliable "; //reachable only if no book found
}
And some last touch, is to use an enhanced for each loop:
public String searchTitle(String titleSearch) {
if (titleSearch == null) return "\n No Books Avaliable ";
for(Book b : collection){
if(titleSearch.equalsIgnoreCase(book.getTitle())){
return "\n Book Avaliable";
}
}
return "\n No Books Avaliable "; //reachable only if no book found
}