是否可以搜索数组并返回值的索引

时间:2013-05-21 22:13:03

标签: java arrays search

我正在编写一个简单的Java程序,它基本上存储了以前在图表中的一系列艺术家;这是我目前为程序编写的代码

package searching;

import java.util.*;

public class Searching {
    public static void main(String[] args) {          
        Scanner scanner = new Scanner(System.in);

        String artists[] = {"Rihanna", "Cheryl Cole", "Alexis Jordan", "Katy Perry", "Bruno Mars",
                        "Cee Lo Green", "Mike Posner", "Nelly", "Duck Sauce", "The Saturdays"};

        System.out.println("Please enter an artist...");
        String artist = scanner.nextLine();
    }
}

我只是想知道,用户是否可以输入其中一位艺术家的名字,获取搜索数组的代码并返回该值的索引?如果是这样,我怎么会这样做,因为我不知道从哪里开始...提前谢谢!

4 个答案:

答案 0 :(得分:5)

使用未排序的数组,一个选项是将艺术家放入列表并使用List.indexOf()

 List<String> artistsList = Arrays.asList( artists );
 ...
 int index = artistsList.indexOf( artist );

如果对艺术家进行了排序,您可以使用Arrays.binarySearch()

答案 1 :(得分:4)

您需要在for循环中遍历artists数组,然后在值等于artist值时返回索引。

    for (int i = 0; i < artists.length; i++) {
        String artistElement = artists[i];
        if (artistElement.equals(artist)) {
            System.out.println(i);
        }
    }

以下是发生在我身上的事情:

Please enter an artist...
Mike Posner
6

答案 2 :(得分:3)

  

我只是想知道,用户是否可以输入其中一位艺术家的名字,获取搜索数组的代码并返回该值的索引?

是的,这是可能的。

由于你不知道从哪里开始,我会说你可以开始浏览数组(可能使用for循环)并验证是否artist变量等于到数组的当前元素。如果它们等于,那么您只需返回数组元素的当前索引即可。如果找不到任何内容,则返回一个默认值,如-1,您可以处理并返回未找到艺术家等消息。

答案 3 :(得分:2)

你可以这样做:

int index = -1;

for (int i = 0; i < artists.length; i++) {
    if (artist.equals(artists[i]))
        index = i;
}

if (index == -1)
    System.out.println("Artist not found");
else
    System.out.println("Index of artist: " + index);
}

这不像tieTYT的解决方案那样雄辩,但是做到了。索引设置为-1。 for循环将每个艺术家与数组中的每个值进行比较。如果找到匹配项,则将索引设置为元素的索引。

在for循环之后,如果索引仍为-1,则会通知用户未找到匹配项,否则将输出相应的艺术家和索引。

for循环的用户是滚动数组内容并将元素与给定值进行比较的最常用方法。通过调用artists [i],可以根据输入String检查数组的每个元素。

相关问题