Reputation: 71
static int findPerson(String n, int NP, Friend[] giftGivers){
int index = 0;
for (int i = 0; i < NP; i++){
if (giftGivers[i].name == n){
index = i;
}
}
return index;
}
I have this code in Java for a method to search through an array of Friends to find the index number of the person with the name input by String n. however i have found that the index number does not set to the index number it is should be. Is it because it is in the if statement?
Upvotes: 1
Views: 252
Reputation: 46438
.equals()
method checks for equality
of two string objects, ==
operator checks if two refrence variables point to the same String object.
In your case you have to use .equals()
method
if (giftGivers[i].name.equals(n))
refer to String API.
Note that if you wanna check if two strings are equal case insensitive use equalsIgnoreCase()
Upvotes: 1
Reputation: 15572
You need to use equals to compare strings not ==
.
==
will compare the object references rather than the actual string value.
If you don't care about case, then there is also an equals method that ignores case
Upvotes: 2
Reputation: 66667
(giftGivers[i].name == n){
should be
(giftGivers[i].name.equals(n)){
String/Object comparison should use .equals()
instead of ==
==
will check for reference equality. equals()
check for object equality.
Upvotes: 1
Reputation: 19856
if (giftGivers[i].name == n)
is wrong, use if (giftGivers[i].name.equals(n))
BTW, there is no need to use NP
. It's C-style, not necessary (actually, pretty dangerous) in Java. Instead of
for (int i = 0; i < NP; i++)
,
just say for (int i = 0; i < giftGivers.length; i++)
Upvotes: 8