简体   繁体   English

搜索ArrayList对象:对象的

[英]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(); 这是我的ArrayList:书籍= new ArrayList();

I have to search objects of Book that contain a title(String). 我必须搜索包含title(String)的Book对象。 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. 由于该方法说searchBookInCollection() ,因此期望它返回一本书或名称或其他内容。 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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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