ArrayList 循环只输出最后一项

Geo*_*lva 2 java loops for-loop arraylist

我正在尝试遍历一个 ArrayList,并将每个索引值与默认值进行比较,如果索引值与默认值匹配,我想返回 true,唯一的问题是,它总是只对索引项返回 true被添加。由于我的类没有 main 方法,因此我在类构造函数初始化期间添加了这些值。

  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;
    }

}
Run Code Online (Sandbox Code Playgroud)

country 参数是从另一个类传递的,该类从用户那里获取国家/地区值。

Mur*_*nik 5

在循环的每次迭代中c,无论其值如何,您都会覆盖,因此您将始终返回最后一个元素的结果。一种解决方案是使用“提前返回”习语并true在找到项目时立即返回:

@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;
}
Run Code Online (Sandbox Code Playgroud)

但是请注意,这只是该contains方法的重新实现,因此您不妨直接使用它:

@Override
public boolean forWeather(String country) {
     return Countries.contains(country.toLowerCase());
}
Run Code Online (Sandbox Code Playgroud)