Pawan
Pawan

Reputation: 32331

How can I set a flag value in an array loop?

I have an array as shown below.

Basically in this array, sometimes thebagdata[i].getSecurityType() may or may not contain values in an array.

 for (int i = 0; i <bagdata.length; i++) {
                if (bagdata[i].getSecurityType() != null) {
                    flag = true;
                } else {
                    flag = false;
                }

            }

I think that my code is overriding the flag value. How can I deal with this?

Upvotes: 1

Views: 3621

Answers (4)

GuruKulki
GuruKulki

Reputation: 26428

If you the flag value to be set true then come out of the loop using break statement.

Upvotes: 1

shift66
shift66

Reputation: 11958

If you want to set flag to true if at least one containsdata you should just set the flag to false before the loop and delete part of else like this:

        flag=false;
          for (int i = 0; i <bagdata.length; i++) {
            if (bagdata[i].getSecurityType() != null) {
                flag = true;
            }
        }

but if you want to remember flag for each element in array you should create an array of flags...

Upvotes: 1

Riz
Riz

Reputation: 10246

Use break; immediate after setting the flag if required. If you want flag against each value, make an array of flags.

Upvotes: 3

Fred
Fred

Reputation: 5006

Depend on what you want to flag, try:

boolean flag = true;

for (int i = 0; i <bagdata.length; i++) {
    flag &= bagdata[i].getSecurityType() != null;
}

Upvotes: 4

Related Questions