【发布时间】: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