【发布时间】: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