2013-02-27 110 views
1

當我試圖返回索引時出現錯誤(必須返回一個int),我看不到我做錯了什麼。如何將Object數組索引與一個int進行比較,並返回索引號?如何返回Object數組的索引?

//x starts at 10000 because the left most number is assumed to be at least a 1. 
/** 
* Search for a book id within the Book object array 
* @param Book - Array of objects with book id, title, isbn, author, and category 
* @param numOfBooks - how many books are in the library 
* @param myBookID - The key to search for 
* @return the index of the array where the key matches 
*/ 
public static int bookSearch (Object[] Book, int numOfBooks, int myBookID) { 
    for (int x = 10000; x <= numOfBooks; x ++) 
     if (Book[x].equals(myBookID)) 
      return x; 
} 
+1

在Java中,你可以通過Book.length得到數組的長度。在Java中,你應該使用小寫變量。 – m0skit0 2013-02-27 11:10:18

+0

這就是我的老師用這些確切的變量名輸入指令的方式......不想違背它。 – trama 2013-02-27 11:15:57

+0

我建議你換教練/課程。 – m0skit0 2013-02-27 12:05:23

回答

4

您需要在最後添加額外的回報,因爲它可能會導致您的條件從未匹配。

public static int bookSearch (Object[] Book, int numOfBooks, int myBookID) { 
    for (int x = 10000; x <= numOfBooks; x ++) { 
     if (Book[x].equals(myBookID)) 
      return x; 
    } 

    return -1; 
} 

在附註中,您可能想要檢查數組的邊界,而不是假設您最多有10000個項目。您還可以利用的事實,所有陣列具有length財產,避免將您的參數之一:

public static int bookSearch (Object[] books, int myBookID) { 
    if(books.length < 100000) return -1; 

    for (int x = 10000; x <= books.length; x++) { 
     if (Book[x].equals(myBookID)) 
      return x; 
    } 

    return -1; 
} 
+0

OH DUH!非常感謝!在我嘗試的所有事情中,我不知道爲什麼它不是其中之一... – trama 2013-02-27 11:11:45

+1

這將始終返回'-1',因爲'Book [x]'是一個永遠不會等於原始'int myBookID'。 – jlordo 2013-02-27 11:13:06

+0

@jlordo - 因爲他傳入了一個對象數組,所以我認爲他將整數與int進行比較,這很好。 int參數將被自動裝箱。 – Perception 2013-02-27 11:15:49

0

應該有外循環return語句,以使函數返回即使一個int循環退出而不滿足條件。

0

如果等於從不匹配,則需要在循環外部返回一個值。 另一個解決方案是如果找不到則拋出異常。

你不能得到一個返回類型不是void的函數的結尾,也不會實際返回一個值(或拋出異常)。

0

這是因爲編譯器看得比你更遠,它也考慮你的書不在數組中的情況。你回報然後

0

如果等於從不匹配,則必須在循環下添加第二個返回值。

2

你可能尋找的東西,如:

public static int bookSearch (Book[] books, int myBookID) { 
    for (int x = 0; x < books.length; x++) 
     if (books[x].getId() == myBookID) 
      return x; 
    return -1; // not found 
} 
0

的問題是,如果裏面的計算的表達式,如果始終是假的if語句裏面的回報可能永遠不會到達。

只需在for循環外添加一個「默認」返回!

2

它只能在JavaScript中使用,

您可以輕鬆找到索引號。從對象的任何屬性對象數組列表

function _findIndexByKeyValue(arraytosearch, key, valuetosearch) { 
    for (var i = 0; i < arraytosearch.length; i++) { 
     if (arraytosearch[i][key] == valuetosearch) { 
      return i; 
     } 
    } 
    return -1; 
} 

應用上述方法類似這樣的

var index = _findIndexByKeyValue(objectArrayList, "id", objectArrayList.id); // pass by value 
if (index > -1) { 
    // your code 
} 

數組列表

var objectArrayList = [{ 
    property1: 10, 
    property2: 11, 
    timestamp: "date-001", 
    id: 1 
}, { 
    property1: 10, 
    property2: 11, 
    timestamp: "date-002", 
    id: 2 
}, { 
    property1: 10, 
    property2: 14, 
    timestamp: "date-002", 
    id: 3 
}, { 
    property1: 17, 
    property2: 11, 
    timestamp: "date-003", 
    id: 4 
}];