2017-06-21 81 views
0

我在努力尋找解決方案,或者至少指向我朝着正確的方向...搜索ArrayList對象:對象的

這裏是我的ArrayList:書=新的ArrayList();

我必須搜索包含標題(字符串)的書的對象。這是我有..

問題是,我只想打印第二條語句,如果它沒有找到。但它似乎正在打印它,因爲它搜索列表中的每個對象?

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

改變它有一個布爾發現標誌

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

非常感謝。我想我沒有考慮在第二個陳述的每一個之外尋找。我的老師提到過不使用休息(在病例陳述之外),因爲我們應該允許循環在大多數情況下自行破壞?你明白他們的意思嗎? – Blackbox10101

+0

*你明白他們的意思嗎?*如果你使用'while'循環或標準'for'來循環,你可以設置'terminating'條件,使它'break'例如'while(!found)'但是因爲您正在使用for-for的每種類型,那麼我如何編碼是好的。 –

+0

@ Michael-Markidis謝謝編輯 –

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