【发布时间】:2018-12-05 22:05:50
【问题描述】:
我在这里的方法在 Eclipse 上遇到了问题。如果在名为 catalog 的数组中找到对象,我需要返回 Country 对象,如果找不到则返回 null。我试图遍历目录并这样做。但是 java 要求我在代码的 for 循环之外添加一个 return 语句。但是,当我在执行该方法时在 for 循环之外添加 return 语句时,它会完全忽略 for 循环,只返回 for 循环之外的语句。
public Country findCountry(String countryname) {
for (int i = 0; i < catalogue.length; i++) {
if (catalogue[i].getName() == countryname) {
return catalogue[i];
} else {
return null;
}
}
}
编辑:在循环之前添加了 foundCountry 变量并在之后返回它。添加了一个中断,并使用 .equals() 比较字符串。获取 NullPointerException。
public Country findCountry(String countryname) {
Country foundCountry = null;
for (int i = 0; i < catalogue.length; i++) {
if (catalogue[i].getName().equals(countryname)) {
foundCountry = catalogue[i];
break;
}
}
return foundCountry;
}
【问题讨论】:
-
也许你的
catalogue数组是空的。或者问题可能是将字符串与 ==(使用等于)进行比较 -
请注意,您实际上并没有在这里循环,您总是在第一次迭代时返回。如果目录长度为零怎么办?将
return null:移到循环外。
标签: java for-loop if-statement return curly-braces