2

I am trying to loop through an ArrayList, and compare each index value to a default value, if the index value matches the default value, I want to return true, the only problem is that, it always returns true only to the index item that is added. Since my class doesn't have a main method, I have added those values during the class constructor initialization.

  public class CountryFinderImpl implements CountryFinder{

    List<String> Countries = new ArrayList<String>();



    public CountryFinderImpl() {

        Countries.add("canada");
        Countries.add("japan");
        Countries.add("usa");

    }

    @Override
    public boolean forWeather(String country) {
        // TODO Auto-generated method stub
        country = country.toLowerCase();
        boolean c=false;


                for(int i=0; i<Countries.size();i++) {
                    if(Countries.get(i).equals(country)) {
                        //System.out.println(country+"Weather available");
                        c=true;
                    }else {
                        //System.out.println(country+"weather unavilable");
                        c=false;
                    }

                }


        return c;
    }

}

The country parameter is passed from another class, which takes the country value from the user.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
George Silva
  • 385
  • 5
  • 13

1 Answers1

5

In each iteration of the loop, you overwrite c, regardless of its value, so you'll always return the result fot the last element. One solution is to use the "early return" idiom and return true immediatly when the item is found:

@Override
public boolean forWeather(String country) {
    country = country.toLowerCase();
    for (int i = 0; i < Countries.size() ;i++) {
         if (Countries.get(i).equals(country)) {
             return true;
         }
    }
    return false;
}

Note, however, that this is just a reimplementation of the contains method, so you might as well just use it:

@Override
public boolean forWeather(String country) {
     return Countries.contains(country.toLowerCase());
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350