IN JAVA: Write recursive method to return true if a given array has element equal to employee emp, or returns false otherwise. Array can be empty or not.
//PRECONDITION: Varible n denotes the number of occupied positions in the array and must be non-negative. Employee class has method getSalary() that returns employee's salary, // and it has method boolean equals(Employee emp) that accept an employee object and returns true if employee calling the equals method is equal as employee emp, and returns // false otherwise. An empty array returns false. Method employeeInRec must be recursive and returns true if array csEmployees has employee emp, and returns false otherwise. public boolean employeeInRec (Employee[] csEmployees, int n, Employee emp) { } |
Program Code [JAVA]
// Since Employee class is not given we are making our own
class Employee {
private String firstName;
private String lastName;
private int numHours;
private double hourlyPay;
// Constructor
public Employee(String firstName, String lastName, int numHours,
double hourlyPay) {
this.firstName = firstName;
this.lastName = lastName;
this.numHours = numHours;
this.hourlyPay = hourlyPay;
}
public boolean equals(Employee emp) {
return ((this.firstName.equalsIgnoreCase(emp.firstName))
&& (this.lastName.equalsIgnoreCase(emp.lastName))
&&
(this.numHours == emp.numHours) && (this.hourlyPay ==
emp.hourlyPay));
}
public double getSalary() {
return numHours * hourlyPay;
}
}
class Main {
// employeeInRec method
public static boolean employeeInRec(Employee[] csEmployees, int n, Employee emp) {
if (n == 0)
return false;
if(csEmployees[n-1].equals(emp))
return true;
else
return employeeInRec(csEmployees, n-1, emp);
}
public static void main(String[] args) {
// Testing employeeInRec method
Employee[] csEmployees = new Employee[3];
csEmployees[0] = new Employee("John", "Clint", 5, 20);
csEmployees[1] = new Employee("Sarah", "Khan", 7, 30);
csEmployees[2] = new Employee("Roxy", "Rush", 8, 25);
Employee emp = new Employee("Sarah", "Khan", 7, 30);
if(employeeInRec(csEmployees, 3, emp))
System.out.println("True: emp is in csEmployees array");
else
System.out.println("False: emp is not in csEmployees array");
}
}
Sample Output:-
----------------------------------------------------------------------
COMMENT DOWN FOR ANY QUERIES!!!
HIT A THUMBS UP IF YOU DO LIKE IT!!!
Get Answers For Free
Most questions answered within 1 hours.