【问题标题】:Linear Sorted Search线性排序搜索
【发布时间】:2015-12-14 22:23:10
【问题描述】:

我创建了这个代码,它是一个图表位置。它应该允许用户输入已经在数组中设置的名称,并且艺术家的位置将在输入不是“结束”时输出

public static void main(String[] args) {
    Scanner kybd = new Scanner (System.in);
    String names = null;

    String [] Artists = new String [];
    String [] Artists = new String []{"Fetty Wap", "Drake", "Miley Cyrus"
    ,"Kanye West","Chris Browna","Tinie Tempah","Robin Thicke","The Weeknd"
    ,"Jay Z","The Wanted"};

    do{
        System.out.println("Please enter name ");
        names = kybd.next();
    } while (!names.equalsIgnoreCase("end")) ;
}

public static int linearSorted(int[] array, int item)
{
    int index = 0;
    while (index < array.length &&
    array[index] != item &&
    array[index] < item)
    {
        index++;
    }

    if (index == array.length ||
    array[index] > item)
    {
        index = -1;
    }
    return index;
}
} 

我遇到的问题是它没有显示图表位置,因为它在数组中排序

【问题讨论】:

  • 您确实意识到数组的一半是空的,因为您只是一遍又一遍地将不同的值插入Artists[1]
  • 将假数据创建为String[] s = new String[] {"foo", "bar", "baz"}; 更简洁,这样数组总是紧凑且大小正确。
  • 我不明白你想在这里做什么。您说您正在尝试allow the user to enter a name already set in the array and the position of the artist will output whilst the input is not "end",但您没有输入该职位,也没有调用您的linearSorted 方法。请在您的问题中提供更多详细信息。
  • @azurefrog 感谢他们提出的建议。我需要程序做的是输出用户按数组顺序输入的名称的位置,例如,如果用户输入“麦莉赛勒斯”,则该位置应输出为 3,因为它存储在位置 3 中。我希望这个让它更清晰
  • 你的数组仍然有很多空元素。艺术家[1] =“克里斯布朗”;艺术家[1] = "Tinie Tempah";表示将相同的元素插入该位置,因此您插入的最后一个元素将是该位置中的元素。因此,您不仅有空白空间,而且还会丢失数据。

标签: java arrays methods linear-search


【解决方案1】:

如果您需要做的只是线性搜索来查找名称索引,那么这应该可以工作

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String name = null;
    String [] Artists = new String []{"Fetty Wap", "Drake", "Miley Cyrus"
            ,"Kanye West","Chris Browna","Tinie Tempah","Robin Thicke","The Weekend"
            ,"Jay Z","The Wanted"};

            do{
                System.out.print("Please enter name: ");
                name = sc.nextLine();
                System.out.println(linearSearch(Artists, name));
            } while (!name.equalsIgnoreCase("end")) ;

}

public static int linearSearch(String[] arr, String name){
    for(int i = 0; i < arr.length; i++){
        if(arr[i].equals(name)){
            return i;
        }
    }
    return -1;
}

【讨论】:

    猜你喜欢
    • 2019-03-02
    • 2014-11-05
    • 2012-08-28
    • 2019-01-26
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多