Pawan
Pawan

Reputation: 32331

Java : How to set the flag value in a array loop

This is my below mehod for Validation .

public boolean validateData(Bagform[] bagdata) {
    boolean flag = false;
    int length = bagdata.length;

    if (length == 2) {
        for (int i = 0; i < bagdata.length; i++) {
            if (bagdata[i].getCallType() == null) {
                flag = true;
            }
        }
    }
    else {
        flag = true;
    }
    return flag;
}

In this basically i am checking that if the getCallType() is not null for any of the values in the array .

If its not null , then its a valid data , so i am setting the flag to true . (Please see the code above )

But for me , i am getting the flag value still as false ( Even though the getCallype() is not null )

Please help me .

Upvotes: 1

Views: 7276

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503090

You're setting the flag to true if the call type is null. I suspect you want:

public boolean validateData(Bagform[] bagdata) {
    boolean flag = true;
    int length = bagdata.length;

    if (length == 2) {
        for (int i = 0; i < bagdata.length; i++) {
            if (bagdata[i].getCallType() == null) {
                flag = false;
            }
        }
    }
    return flag;
}

It's not clear why you're only performing this validation when there are exactly two entries in the array though. Unless that's really deliberate, I'd have written this has:

public boolean validateData(Bagform[] bagdata) {
    for (Bagform form : bagdata) {
        if (form.getCallType() == null) {
            return false;
        }
    }
    return true;
}

Upvotes: 4

Related Questions