2015-11-29 55 views
0

對不起,初學者編碼器在這裏,我不擅長解釋事情,但我想知道如何返回一個數組的第一個書對象?返回數組中第一個作者寫的第一個Book對象?

這裏是我的代碼:

public Book getBookWrittenBy(String firstName){ 
    Book writtenBy = null; 

    if((inventory == null) || (inventory.length == 0)){ 
     return null; 
    } 
    for(int i=0; i < inventory.length; i++){ 
     if(inventory[i] != null && writtenBy == null || inventory[i].getTitle().equals(firstName)){ 
      writtenBy = inventory[i]; 
     } 

    } 
    return writtenBy; 
} 

當我測試在BlueJ的編譯器的代碼返回從作者標題但與firstNameBook對象的第一個實例。

這是我需要使用方法:

public Book getBookWrittenBy(String firstName)

  • 返回與此名字

一個作者寫的第一Book對象。如果任何人可以幫助我的代碼這將不勝感激。提前謝謝了。

+0

東西在這裏的叢林腥。發佈Book類以及如何聲明並填充所謂的inventory []數組。 – DevilsHnd

回答

0

我建議以下解決方案:

public Book getBookWrittenBy(String firstName){ 
    if((inventory == null) || (inventory.length == 0)){ 
     return null; 
    } 
    for(int i=0; i < inventory.length; i++){ 
     if(inventory[i] != null && inventory[i].getTitle().equals(firstName)){ 
      return inventory[i]; 
     } 

    } 
    return null; 
} 

您可以簡單地返回庫存[I]這將退出隱含的for循環並返回書的第一個實例。

+0

感謝這個建議,但是當我這樣做的時候,它返回一個空值 – Tre

+0

,請在每個「返回null」之前添加System.out.println(「某些文本」)。要查看使用哪一個。您可以使用調試器。 – Marcinek

0

佈局略有不同。當您在特殊輸入時儘早退出該方法時,它有助於調試代碼並使循環更易於理解。爲每個循環使用一個簡化代碼。

interface Book { 
    String getFirstNameOfAuthor() 
    String getLastNameOfAuthor() 
} 

public Book getBookWrittenBy(Book[] inventory, String firstName) { 
    if (null == inventory || null == firstName) return null; 

    for (Book book : inventory) { 
    if (firstName.equals(book.getFirstName)) return book; 
    } 

    return null; 
} 
+0

嗨,感謝您的建議,但我不能使用每個循環我必須使用for循環。 – Tre

0

如果您只是將return語句放入for循環中,您將在第一次出現時返回所找到的內容。你的方式,你回來了你找到的最後一個,因爲你每次找到一個書時,將該作者寫的新書分配給變量writtenBy。嘗試改寫爲週期:

for(int i=0; i < inventory.length; i++){ 
if(inventory[i].getTitle().equals(firstName)) 
    return inventory[i]; 
} 
+0

嗨,感謝您的建議,但是當我這樣做時,它仍然返回作者的任何書,我需要返回的是我作爲作者的第一本數組。 – Tre

+0

你確定你用這個替換了你的週期嗎?我覺得很奇怪,這個應該返回數組中的第一個結果。 – Matt

+0

嗨,是的,我做了什麼是它返回數組的第一個元素,而不是作者的第一本名字firstName – Tre

0

我想你應該避免返回null,這將是更好地使用Optional類。

所以您的解決方案可能看起來像:

public Optional<Book> getBookWrittenBy(String firstname) { 
    return Stream.of(inventory) 
     .filter(book -> firstname.equals(book.getAuthor())) 
     .findFirst(); 
相關問題