Issue
Hi so I have two classes Employee and Department. My main function reads off a .txt file filled with employee names, salaries, departments, and positions. My Employee class is just getters and setters. An list of arraylists are made to represent the employees and I'm not sure how I would find the minimum salary of each of the departments. To find the maximum salary I did this in my department class.
public class Department {
String dept;
List<Employee> employees;
double minSal;
double maxSal;
public void addEmployee(Employee emp){
maxSal = 0.0;
if (maxSal < emp.getSalary()) {
maxSal = emp.getSalary();
}
but I'm not sure how to get the minimum salary. My idea was to get the salary of one of the employees from each department and use that as a starting point for
if (minSal > emp.getSalary()) {
minSalary = emp.getSalary();
}
But I realized I had no idea what to do. Can I get some help with this?
Solution
There is a special number, Double.POSITIVE_INFINITY
, which is greater than any number representable with double
. You can use it as a starting point for searches of a minimum:
double minSalary = Double.POSITIVE_INFINITY;
...
if (minSal > emp.getSalary()) {
minSalary = emp.getSalary();
}
Another common trick is to set minSalary
to the first element of a list, and then start searching from the second element.
Answered By - Sergey Kalinichenko
Answer Checked By - Mildred Charles (JavaFixing Admin)