user3263978
user3263978

Reputation: 193

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

Upvotes: 0

Views: 8669

Answers (1)

wastl
wastl

Reputation: 2641

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

Upvotes: 2

Related Questions