0

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

user3263978
  • 193
  • 1
  • 2
  • 14
  • If you used a list instead of an array you could use its indexOf method and do so that in one line. – assylias May 23 '14 at 23:16
  • 4
    You need to increment `location++;` after calling `currentArtist = myArray[location];`, otherwise you'll end up with an index that is out of bounds (as the error suggests). Also don't compare String values using `==`. – Alexis C. May 23 '14 at 23:17
  • @ZouZou okay thank you that's removed the error, but now it only prints out the location if I type a string that doesn't have a space in the middle any idea why? – user3263978 May 23 '14 at 23:24

1 Answers1

2

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

wastl
  • 2,643
  • 14
  • 27