I am trying to prepare an employee search program.
Requirements:
I have an
ArrayList"employee" which is holding data of multiple employees (like :name,employeeID,location,DOJ, etc).I need to prepare a method to say
findEmployeewhich will expect anameas input, and will return all the associated details with that employee.In case no such employee was found, then it should throw an exception.
My code:
private static List<Employee> employee = new ArrayList<>();
public Employee findEmployee(String Name) throws emplyeeNotFoundException {
for(Employee value : employee) {
if(value.getName().equals(Name)) {
return value;
}
else {
throw new emplyeeNotFoundException(Name);
}
}
}
Here Employee is the main class and getName() is the method to get the name of employee.
Issue:
- I am aware that above logic will not work as it will throw an exception every time
ifcondition does not meet the requirement.
Can anyone suggest to me how I need to write this code so that it will check the complete employee list and only throw an exception when no data found?
Also, if it found the employee name in ArrayList it should return all its details and come out of the loop?