[英]method requiring return statement outside for loop
我在这里的方法在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[i].getName() == countryname
至
catalogue[i].getName().equals(countryname)
并且不要从else
部分return null
。 循环完成后,执行以下操作:
public Country findCountry(String countryname) {
for (int i = 0; i < catalogue.length; i++) {
if (catalogue[i].getName().equals(countryname)) {
return catalogue[i];
}
}
return null;
}
请注意,它不是Null证明。
具有流用法的另一个版本(需要Java 8或更高版本)并检查catalogue
是否为null
:
public Country findCountry(String countryName) {
if (catalogue == null) {
return null;
}
return Arrays.stream(catalogue)
.filter(country -> country.getName().equals(countryName))
.findAny()
.orElse(null);
}
去掉
else {
return null;
}
并将其放在您的for循环之外
return null;
如果国家/地区不在目录中的第一个元素,则您的代码将返回null。 它不会遍历它。
您可以使用null初始化返回值,并且仅在循环中找到它时才设置它:
public Country findCountry(String countryname) {
// initialize a Country with null
Country foundCountry = null;
// try to find it
for (int i = 0; i < catalogue.length; i++) {
if (catalogue[i].getName().equals(countryname)) {
// set it if found
foundCountry = catalogue[i];
}
}
// if not found, this returns null
return foundCountry;
}
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;
}
找到后,打破循环以提高性能。 在未找到时,默认情况下它将返回null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.