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

[复制链接]
查看11 | 回复1 | 2009-6-7 11:59:10 | 显示全部楼层 |阅读模式
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.getName()))
{

return em;

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,2780);
em[2]=new Employee("王五",12348,23,3000);
System.out.println(Employee.SEN(em,"张三").getAge());

}
}
上面的提示是出错的原因,我有以下的不解:
1 em 是类型为Employee的对象数组,那么em就是类型为Employee的对象,但是为什么还有提示返回的数据类型有误呢?
2 为什么在这里break就用不了

回复

使用道具 举报

千问 | 2009-6-7 11:59:10 | 显示全部楼层
因为你是for循环的if里面返回,但是如果你的if一直执行不到呢?那这个方法返回什么?你必须保证程序的每条路径都可以返回一个Employeebreak的问题编译器已经告诉你了Unreachable code,无法到达的代码。你上面一句话已经return了,break还有可能执行么?...
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行