我有一个字符串数组,这些字符串是艺术家,当用户在控制台中键入其中一个字符串时,我希望它打印出该字符串在数组中的位置;所以这是我目前的代码
String artist;
int location = 0;
String currentArtist;
String [] myArray = {"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 artists name: ");
Scanner scanner = new Scanner(System.in);
artist = scanner.next();
while (location < myArray.length) {
location++;
currentArtist = myArray[location];
if (artist == currentArtist) {
System.out.println(location);
}
}
但是当我运行它并输入一个名字时,我得到以下错误;
线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:10 at chartposition.ChartPosition.main(ChartPosition.java:26) Java结果:1
和第26行是这个;
currentArtist = myArray[location];
我不确定我哪里出错了所以任何帮助都会受到赞赏。提前谢谢!
编辑1
我已经改变了if语句;
if (artist == currentArtist) {
System.out.println(location);
}
到此;
if (artist.equals(currentArtist)) {
System.out.println(location);
}
它现在打印出数组中字符串的位置,但仍然会出现相同的错误
答案 0 :(得分:2)
你过早地递增计数器,因为在最后一次迭代中它具有值myArray.length
在循环结束时移动location++
,或使用for循环