0

我正在尝试生成将搜索从数组末尾开始的元素并从头开始工作的代码,直到找到我要查找的内容。到目前为止我有这个,但它似乎没有工作:

     for (int i = randomList.length - 1; i > 0; i--)
            {
             if (randomList[i].equals(findThis))
                {
                    System.out.println("The index of what you're looking for in the array is: " + i);

                }                
            }

当我编译并运行它时,它会产生与此相同的答案:

     for (int j = 0; j < randomList.length; j++)
            {
            if (randomList[j].equals(findThis))
                {
                    System.out.println("What you're looking for is located at this index: " + j);
                }           
            }

这很奇怪,因为它从数组的前面开始,一直到最后。我很感激所有的帮助!

4

6 回答 6

3

获取索引的一种快速方法是执行以下操作:

int idx = randomList.lastIndexOf(findThis);

简单的一行代码,将返回给定对象的最后一个索引。如果你想要第一个索引,还有这个:

int idx = randomList.indexOf(findThis);
于 2012-12-13T20:59:14.160 回答
2

注意:

for (int i = randomList.length - 1; i > 0; i--)

应该:

for (int i = randomList.length - 1; i >= 0; i--)

但否则它看起来是正确的;你确定你用你的IDE正确清理/重建吗?

如果可以,请提供额外的上下文,例如代码在哪里运行、您的数据是什么,以及预期与实际结果是什么。

于 2012-12-13T20:52:53.320 回答
1

如果搜索的值在您的数组中多次存在,您只会得到不同的答案。顺便提一句。如果您想检查数组中的第一个元素,您的条件应该是 i >= 0。

于 2012-12-13T20:53:45.520 回答
0

如果你有一个数组:

[“狗”、“猫”、“有袋动物”、“胡椒博士”、“百事可乐”]

那么无论你从哪个方向搜索,“Dr. Pepper”的索引都将始终为 3。

编辑:我们在这里使用 0 索引数组。:D

于 2012-12-13T20:53:51.663 回答
0

当数组的元素等于您正在寻找的元素时,您正在显示i和值是数组中元素的位置。j

您的代码是正确的,您只是返回要搜索的元素的索引,因此从开头或结尾开始它将返回相同的索引(相同的元素位置),除非您有多个等于该元素的元素你正在寻找然后你会注意到差异。

为了了解发生了什么,您应该更改您的代码,如下所示:

 for (int i = randomList.length - 1; i > 0; i--)
        {
         System.out.println("Actual index =" + i);
         if (randomList[i].equals(findThis))
            {
                System.out.println("The index of what you're looking for in the array is: " + i);

            }                
        }

当我编译并运行它时,它会产生与此相同的答案:

 for (int j = 0; j < randomList.length; j++)
        {
         System.out.println("Actual index =" + j);
         if (randomList[j].equals(findThis))
            {
                System.out.println("What you're looking for is located at this index: " + j);
            }           
        }
于 2012-12-13T20:54:54.510 回答
0

您正在返回找到的元素的索引,该索引在任一方向上都是相同的(即array[4],无论您如何搜索,它都是相同的)

如果你想在另一个方向计数,你可以这样做:

for (int i = 0; i < randomList.length; i++)
{
  if (randomList[randomList.length - i - 1].equals(findThis))
    {
      System.out.println("The count from the back of the array is: " + i);
    }                
}
于 2012-12-13T20:56:04.327 回答