Java:在数组中查找整数

时间:2015-03-11 18:04:35

标签: java arrays integer min

问题: 创建一个名为findElementIndex的静态方法,该方法将整数和整数数组作为输入参数,并返回该值出现的最小索引。如果该值不在数组中,则该方法应返回-1。   实施例: 值:3 theArray:{10,3,6,3,8,10} ==> 1 或值:10 theArray:{11,3,6,7,9,60} ==> -1

public static int findElementIndex (int value, int [ ] theArray) 
{  } 

我的代码:无法编译&我想我已经看过很多次才发现错误。

int index = 0;
int n = -1;

for(int i =0; i < theArray.length; i++) 
    if(value == theArray[i]) {
        index = i; 
        return index; 
    }
    else {
        return n;
    }

谢谢。

3 个答案:

答案 0 :(得分:0)

我把你的代码放到Eclipse中,编译器抱怨该方法必须返回int类型的结果。

编译器说的错误是如果你的数组以0长度传入,你的for循环将永远不会进入if语句,所以你需要在for循环之外有一个额外的return语句。

您的编译器不会抱怨的另一个逻辑错误是您使用了else语句。这意味着如果数组长度超过0,则在第一次测试后,您将立即退出该函数并返回0或-1。

例如:

public static int findElementIndex(int value, int[] theArray) {
    int index = 0;
    int n = -1;
    for (int i = 0; i < theArray.length; i++) {
        if (value == theArray[i]) {
            index = i;
            return index;
        }
    }
    return -1; // if the array was length 0, your for loop will not run.
}

此外,请使用适当的括号

没有括号是一个非常愚蠢的想法。

您可能会意外地编写这样的代码,您希望在for循环中运行3 do this行:

for (condition)
    do this
    do this 2
    do this 3

但实际上意味着

for (condition) { 
    do this 
}
do this 2
do this 3

遗漏了do this 2do this 3 - 而不是你所期待的。调试没有括号也很痛苦。如果只是你把括号放在第一个镜头上......你甚至不会遇到这个问题。

答案 1 :(得分:0)

  private static boolean inArray(int value, int[] array) {

    for (int arrayEntry : array) {
      if (value == arrayEntry) {
        return true;
      }
    }
    return false;
  }

答案 2 :(得分:-1)

你有一些奇怪的代码格式,但你也错过了一个关键步骤 - 如果你已经完成所有的值并且没有找到它,你只想返回-1!此外,您不需要在变量中存储值只是为了立即返回它们!

试试这个:

int index = 0;
for(int i =0; i < theArray.length; i++){
    if(value == theArray[i]) {
        return i; //returns where we found it if it matches
    }
}
return -1; //this line is only reached if we didn't already return