Win a copy of Rust Web Development this week in the Other Languages forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Getting values back from an array

 
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you. This works perfectly.
reply
    Bookmark Topic Watch Topic
  • New Topic