有关如何从方法中返回数组的单个元素

来源:百度知道 编辑:UC知道 时间:2024/04/28 03:04:24
public class Employee {
String name;
int number;
int age;
int salary;
public Employee(String name,int number,int age,int salary)
{
this.name=name;
this.number=number;
this.age=age;
this.salary=salary;
}

public void setAge(int age)
{
this.age=age;
}
public int getAge()
{
return age;
}

public static Employee SEN(Employee[] em,String str)//提示This method must return a result of type Employee
{

int i=0;
for(;i<em.length;i++)
{
if(str.equals(em[i].getName()))
{
return em[i];
break;//提示Unreachable code
}
}
}

}
class EmployeeTest
{
public static void main(String args[])
{
Employee[] em=new Employee[3];
em[0]=new Employee("张三",123456,23,2500);
em[1]=new Employee("李四",12357,22,278

因为你是for循环的if里面返回,但是如果你的if一直执行不到呢?那这个方法返回什么?你必须保证程序的每条路径都可以返回一个Employee

break的问题编译器已经告诉你了Unreachable code,无法到达的代码。你上面一句话已经return了,break还有可能执行么?