gpt4 book ai didi

java - 如何返回对象数组的索引?

转载 作者:行者123 更新时间:2023-11-29 10:16:57 27 4
gpt4 key购买 nike

尝试返回索引时出现错误(必须返回一个整数),我看不出我做错了什么。如何将 Object 数组索引与 int 进行比较,并返回索引号?

//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;
}

最佳答案

你需要在最后添加一个额外的 return,因为你的 if 条件可能永远不匹配。

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

关于java - 如何返回对象数组的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15110534/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com