1
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?

1
  • No need to continue the loop once you have found the person. { for(int i = 0; i < giftGivers.length; i++) if (...) { return i; } } or { int i = 0; while(i < giftGivers.length && !giftGivers[i].name.equals(n)) { i++; } return i; } Commented Oct 30, 2012 at 21:22

4 Answers 4

8

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++)

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for the suggestions. I actually had to add "break;" in the if statement to make it work.
2

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

Comments

1
(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.

Comments

1

.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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.