【问题标题】:ArrayList looping only outputs the last item [duplicate]ArrayList循环仅输出最后一项[重复]
【发布时间】:2020-07-07 00:13:39
【问题描述】:

我正在尝试遍历一个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;
    }

}

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

【问题讨论】:

  • 在循环中:if(Countries.get(i).equals(country)) { return true; } 循环之后,return false; -- 所以如果循环中没有匹配项,则默认为 false
  • 但是即使我在arraylist中传递了一些东西它仍然返回false,它只对arraylist中的最后一项返回true
  • 循环可以替换为return countries.contains(country.toLowerCase());
  • 这个方法到底应该做什么?如果要从中返回多个值,则必须创建一个集合并返回它。
  • 你的循环并没有在找到国家的时候停止,你需要打破循环,在c=true之后添加break;

标签: java loops for-loop arraylist


【解决方案1】:

在循环的每次迭代中,您都会覆盖 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;
}

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

@Override
public boolean forWeather(String country) {
     return Countries.contains(country.toLowerCase());
}

【讨论】:

    猜你喜欢
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 2017-10-25
    • 2021-08-14
    相关资源
    最近更新 更多