Joe
Joe

Reputation: 82594

if statement OR logic oddity

I'm calling this function from a jUnit test case with the following information:

// abbr = "US";
// Countries  = array of two objects one with iso2 = "us"
public Country getCountryFromAbbr(String abbr) {
    abbr = abbr.toLowerCase();
    for (int i = 0; i < Countries.size(); i++) {
        Country country = Countries.get(i);
        String iso2 = country.ISO2.toLowerCase();
        String iso3 = country.ISO3.toLowerCase();

        if (iso2.equals(abbr) || iso3.equals(abbr)) {
            return country;
        }
    }

    return null;
}

When I debug, the second object with ISO2 of us iso2.equals(abbr) is true and the other is false. However, country is not returned and the debugger finishes the loop and returns null.

I'm confused as true || false is true. Am I missing something?

Here's the mock of the countries:

    List<Country> Countries = new ArrayList<Country>();
    Country country = new Country();
    country.CountryId = 1;
    country.CountryName = "Great Britian";
    country.ISO2 = "GB";
    country.ISO3 = "GBR";
    Countries.add(country);

    Country usa = new Country();
    usa.CountryId = Studio.USA_COUNTRY_ID;
    usa.CountryName = "United States of America";
    usa.ISO2 = "US";
    usa.ISO3 = "USA";
    Countries.add(usa);
    return Countries;


EDIT: I'm using Eclipse and debugging using my Droid X 2.3.3

Upvotes: 3

Views: 224

Answers (2)

James Bassett
James Bassett

Reputation: 9868

This looks like a job for Enum! (whoooooosh!)

public enum Country {

    GREAT_BRITAIN("GB", "GBR"),
    USA("US", "USA");

    private String iso2;
    private String iso3;

    private Country(String iso2, String iso3){
        this.iso2 = iso2;
        this.iso3 = iso3;
    }

    public static Country getCountry(String a){
        for (Country c : Country.values()){
            if (c.iso2.equalsIgnoreCase(a) || c.iso3.equalsIgnoreCase(a)){
                return c;
            }
        }
        return null; // no country found!
    }

}

If Country is immutable (you're not going to change any values inside it), then this is a neat way of doing it - and you can add id and name as attributes as well. And expose getters if you need access to those attributes.

Your current method accesses Countries as an instance variable, instead of as an argument to the method, so it's possible there are side-effects there.

Upvotes: 0

Lalit Poptani
Lalit Poptani

Reputation: 67286

Does it work fine with simple if condition?

if (iso2.equals(abbr)) {
            return country;
        }
if(iso3.equals(abbr)){
       return country;
}

Upvotes: 1

Related Questions