没有退货声明

问题描述 投票:0回答:3

我写了一个方法来打印名为 myEmployees 的数组中存在的员工的详细信息。练习说我应该返回一个整数,特别是对象 employee 的索引,我按照要求做了,但它说没有 return 语句。

private int findEmployeeByName(String empName) {
    for(Employee e: this.myEmployees) {
        if(e!=null && e.getEmpName().equals(empName))  {
            return e.getEmpName().indexOf(empName);
        }
    }
}
java arrays object return indexof
3个回答
0
投票

你需要在 for 循环之后有一个 return 语句,以防

this.myEmployees
为空,即使你肯定知道这永远不会发生。

所以只需返回 -1

您的代码不会返回任何内容的另一个地方是,当员工姓名不在列表中时


0
投票

这样想,

在您的方法中,如果根本没有机会满足

if (condition)
,那么该方法将返回什么?

你的情况,

如果你一直找不到给定名字的员工,你想如何处理return statement,由你决定。

您可以返回 -1 或任何

integer
(记住,您不应该使用作为索引的值).

您可以从调用方法的地方处理它。

int index = findEmployeeByName("Barbara Riga");

if (index == -1) {
  System.out.println("Employee not found!");
} else {
  System.out.println("Index of the employee: " + index);
}

0
投票

试试这个,

private int findEmployeeByName(String empName) {
   for(Employee e: this.myEmployees) {
      if(e!=null && e.getEmpName().equals(empName))  {
          return e.getEmpName().indexOf(empName);
      }
   }
   return -1;
}
© www.soinside.com 2019 - 2024. All rights reserved.