搜索ArrayList对象:对象的

时间:2017-06-21 04:17:01

标签: java

我努力寻找解决方案,或者至少指出我正确的方向......

这是我的ArrayList:books = new ArrayList();

我必须搜索包含标题(String)的Book对象。这就是我的......

问题是我只想打印第二个语句,如果找不到。但它似乎是在搜索列表中的每个对象时打印它?

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

2 个答案:

答案 0 :(得分:2)

将其更改为具有布尔找到的标志

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

答案 1 :(得分:0)

由于该方法显示searchBookInCollection(),因此应该返回书籍或名称或其他内容。这提供了另一种解决方案,

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