简体   繁体   中英

Search ArrayList object : object's

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");
        }
    }
 }

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");
       }
}

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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM