Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Getting values back from an array  RSS feed

 
Dan Grindstaff
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a method that uses an array to search for the index of a String parameter. I have an if statement embedded in a for loop designed (intended) to return the index when found. Instead I keep getting back the default return value. I know the String parameter is in the array. Here is the code:

protected int getNameIndex(String name) {
for ( int i=0; i<nameArray.length; i++) {
if (nameArray[i] == name) {
return i;
}
}
return -1;
}

Can someone explain to me why the method is not returning the index value?
 
Renato Losio
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nameArray[i] == name

shoulb be:

nameArray[i].equals(name);

Better test if the value is null too before calling equals.

Cheers,

Renato
 
Dan Grindstaff
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. This works perfectly.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!