0

I struggled to find a solution or at least to point me in the right direction...

Here is my ArrayList: books = new ArrayList();

I have to search objects of Book that contain a title(String). Here is what I have..

The problem being is that I only want to print the second statement if it is not found. But it seems to be printing it as it searches each object in the list?

public void searchBookInCollection(String title) 
{
    for (Book book : books)
    {
        if(book.getTitle().equalsIgnoreCase(title)) 
        {
            book.displayBookInformation();
        }
        else
        {
            System.out.println("Nope we don't have it");
        }
    }
 }
0

2 Answers 2

2

change it to have a boolean found flag

public void searchBookInCollection(String title) 
{
      boolean found = false;
      for (Book book : books)
      {
            if(book.getTitle().equalsIgnoreCase(title)) 
            {
               book.displayBookInformation();
               found = true;
               break;  // no point to keep going? 
            }
       }
       if (!found)
       {
           System.out.println("Nope we don't have it");
       }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much. I guess I didn't consider looking outside of the for each for the second statement. My teacher has mentioned about not using breaks(outside of case statements) because we should allow the loop to break itself in most situations? Do you understand what they mean?
Do you understand what they mean? if you are looping using a while loop or standard for you can just set the terminating condition, cause it to break e.g. while (!found) But as you are using a for-each type of for then how I coded is good.
@ScaryWombat No problem. Any time.
0

Since the method says searchBookInCollection() it is expected to return a book or a name or something. This gives an alternative solution,

public String findBook(String title) { // "InCollection" does not help end user, "find" follows standard naming convention
    for (String book : books) {
        if (book.equalsIgnoreCase(title)) {
            return book; // This is debated, if you want "one return" here, use temporary variable.
        }
    }
    throw new NoSuchElementException("Title was not found!"); // Throw gives the end user a chance to handle the exception.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.