user2209644
user2209644

Reputation: 711

Boolean won't change even if the condition is met

The following method adds an object of type Member to an array:

public boolean addMember(Member m) {
    boolean result = false;
        for(int i = 0; i < members.length; i++){
            if(members[i] == null){


                members[i] = m;
                result = true;
            }
        }


    return result;
}

as you can see, I also return a boolean result if the current position was null. The problem is that, even though the condition is met - the object is added, it displays it no problem - the result boolean always stays false. Why? and how can I make it change?

Upvotes: 0

Views: 221

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48723

You need a break

public boolean addMember(Member m) {
    boolean result = false;

    for (int i = 0; i < members.length; i++) {
        if (members[i] == null) {
            members[i] = m;
            result = true;
            break;
        }
    }

    return result;
}

Or event better, no need for a flag:

public boolean addMember(Member m) {
    for (int i = 0; i < members.length; i++) {
        if (members[i] == null) {
            members[i] = m;
            return true;
        }
    }

    return false;
}

Upvotes: 0

foobarfuzzbizz
foobarfuzzbizz

Reputation: 58725

Nothing is probably being added. It probably wasn't null to begin with, so the loop never runs, which is why the boolean is false at completion.

Actually, this seems like the correct behavior, since if there is not a null space in the members array, the new element does not overwrite existing elements, so false is correct here.

Upvotes: 1

Related Questions