Java 中的 searchForItemInArray - 嵌套 For 循环
Java 说“表达式的类型必须是 Array 类型,但它解析为 Int”,
我希望为解决方案做一个嵌套的 For 循环,但也欢迎任何其他更优雅的建议。
public class ArraySearch {
public static int searchForItemInArray(int needle, int[] haystack) throws Exception {
for (int i = 0; i <= needle; i++) {
for (int j = 0; j < haystack.length; j++) {
if (needle[i] == haystack[j]) {
}
}
}
return -1;
}
}
Java says ''the type of the expression must be Array type but it resolved to Int"
I'm looking to do a nested For Loop for the solution, but any other more more elegant suggestions are also welcome.
public class ArraySearch {
public static int searchForItemInArray(int needle, int[] haystack) throws Exception {
for (int i = 0; i <= needle; i++) {
for (int j = 0; j < haystack.length; j++) {
if (needle[i] == haystack[j]) {
}
}
}
return -1;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
针是一个int变量,因此不是阵列的一部分。
修复if语句的答案是
针== haystack [j]
needle is an Int variable so isn't part of an array.
The answer to fix the IF statement was
needle == haystack[j]
如果实际上是您想要的,则在Arrray中搜索项目,那么您不需要嵌套即可进行循环。
如果针是您要搜索的项目,而干草堆是数组,则需要一次解析数组,仅使用一个来进行循环,并在每个步骤中检查当前项目是否等于搜索的元素。
If searching for an item in an arrray is actually what you want, then you don't need a nested for loop.
If the needle is the item that you are searching for and the haystack is the array, you need to parse the array one time, using only one for loop and check at each step if the current item is equal to the searched element.
看起来您正在该数组中搜索针的索引。如果这是真的,那么您的代码可以如下所示:
It looks like you are searching index of the needle it that array. If it is true, than your code can be as follows: