简体   繁体   中英

Using a while loop to iterate through an array of strings and get position java

I have an array of strings which are artists and when a user types one of the strings into the console I want it to print out the position of that string in the array; so this is the code I have at the moment

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);
    }
}

But when I run this and enter a name in I get the following error;

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at chartposition.ChartPosition.main(ChartPosition.java:26) Java Result: 1

and line 26 is this;

currentArtist = myArray[location];

I'm not sure where I'm actually going wrong so any help would be appreciated. Thanks in advance!

EDIT 1

I've changed the if statement from this;

if (artist == currentArtist) {
    System.out.println(location);
}

to this;

if (artist.equals(currentArtist)) {
    System.out.println(location);
}

It now prints out the location of the string in the array but still get the same error

You are incrementing the counter too early, because of that in the last iteration it has the value myArray.length

Move location++ at the end of the loop, or use a for loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM