【问题标题】:Java: Finding an Integer in an ArrayJava:在数组中查找整数
【发布时间】:2015-05-13 16:29:02
【问题描述】:

问题: 创建一个名为 findElementIndex 的静态方法,它接受一个整数和一个整数数组作为输入参数,并返回该值出现的最小索引。如果该值不在数组中,则该方法应返回 -1。 示例: 值:3 数组:{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;
    }

谢谢。

【问题讨论】:

  • 第 1 步:以可读的方式格式化您的代码。第 2 步:仔细查看编译器给出的有用错误。
  • 你收到什么编译错误?
  • 你忘了在你的 for 循环体周围放大括号
  • @alfasin:技术上,他/她不需要它们。不过,我会把它们放在那里。
  • @Minty:您更改了代码,而不仅仅是修复了格式。更改问题中的代码是不合适的,除非您正在执行诸如将评论中的内容从 OP 移动到问题中。

标签: java arrays integer min


【解决方案1】:

我把你的代码放到 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 - 这不是您所期望的。不带括号进行调试也很痛苦。如果只是在第一张照片中放入括号..你甚至不会遇到这个问题。

【讨论】:

    【解决方案2】:
      private static boolean inArray(int value, int[] array) {
    
        for (int arrayEntry : array) {
          if (value == arrayEntry) {
            return true;
          }
        }
        return false;
      }
    

    【讨论】:

      【解决方案3】:

      你有一些奇怪的代码格式,但你也错过了一个关键步骤 - 如果你已经完成了所有值但没有找到它,你只想返回 -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
      

      【讨论】:

      • 索引将始终为 0
      猜你喜欢
      • 1970-01-01
      • 2017-09-07
      • 2017-04-15
      • 1970-01-01
      • 2014-12-21
      • 2014-02-06
      • 2015-12-08
      • 1970-01-01
      相关资源
      最近更新 更多