简体   繁体   中英

Setting a variable to a value in if statement

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?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM