Java 返回对象或null时缺少return语句
我是一名学生,这是一个练习,这是该方法的目标: 此方法应返回运动员数组的第一个元素,该元素的名称与 名称参数。如果没有匹配的运动员,则返回null 由于某种原因,我得到了这个错误Java 返回对象或null时缺少return语句,java,compiler-errors,return,Java,Compiler Errors,Return,我是一名学生,这是一个练习,这是该方法的目标: 此方法应返回运动员数组的第一个元素,该元素的名称与 名称参数。如果没有匹配的运动员,则返回null 由于某种原因,我得到了这个错误 TestAthletes.java:15: error: missing return statement } 这是我的代码: public class TestAthletes{ public static Athlete findAthleteByName(Athlete[] athletes, Str
TestAthletes.java:15: error: missing return statement
}
这是我的代码:
public class TestAthletes{
public static Athlete findAthleteByName(Athlete[] athletes, String name){
for(int i=0; i<athletes.length; i++){
if(name.equals(athletes[i].getName()))
return athletes[i];
else
return null;
}
}
}
公共类测试运动员{
公共静态运动员findAthleteByName(运动员[]运动员,字符串名称){
对于(inti=0;i,编译器告诉您,如果您碰巧到达了方法的末尾,那么没有返回语句来返回任何内容
并不是说您的代码正在做您希望它做的事情,但无论如何,您应该放一个return语句,可能是:
return null;
在方法块的末尾。我想你的意思是
public class TestAthletes{
public static Athlete findAthleteByName(Athlete[] athletes, String name){
for(int i=0; i<athletes.length; i++){
if(name.equals(athletes[i].getName()))
return athletes[i];
}
return null;
}
}
公共类测试运动员{
公共静态运动员findAthleteByName(运动员[]运动员,字符串名称){
对于(int i=0;i您也需要在for
循环之后有一个return语句,因为长度可以是0,这意味着for
循环的主体永远不会执行。您的return null
语句应该在循环之外。当前,如果第一个值不存在,它将返回null
“不匹配
public static Athlete findAthleteByName(Athlete[] athletes, String name){
for(int i=0; i<athletes.length; i++){
if(name.equals(athletes[i].getName()))
return athletes[i];
}
return null;
}
公共静态运动员findathletbyname(运动员[]运动员,字符串名称){
对于(int i=0;ii)如果数组为空,则永远不会返回。