2013-04-25 38 views
1

嗨,我有兩個班員工和部門。我的主要功能是讀取一個包含員工姓名,薪水,部門和職位的.txt文件。我的Employee類只是getters和setter。爲了表示員工,我列出了一個列表列表,我不確定我會如何找到每個部門的最低工資。爲了找到我的部門班級的最高工資。如何在Java中找到僱員名單的最低工資?

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(); 
     } 

但我不知道如何獲得最低工資。我的想法是讓每個部門的員工之一的工資,並以此作爲一個起點

if (minSal > emp.getSalary()) { 
    minSalary = emp.getSalary(); 
} 

但我意識到,我不知道該怎麼做。我可以得到一些幫助嗎?

+3

爲什麼不使用for循環的迭代ArrayList在循環時檢查最低工資嗎? – 2013-04-25 01:50:53

+0

我看到它之前被問過,但我真的不明白如何將它用於我的情況,我不確定如何使用循環遍歷arraylist。我最近剛剛開始使用java。 – user1869703 2013-04-25 01:55:31

+0

您應該參閱Java教程並閱讀有關for循環的使用。掌握學習Java所需的一項技能就是如何自行學習。 Java教程是一個很好的資源。 Google可以幫助您找到它。 – 2013-04-25 01:58:36

回答

0

有一個特殊號碼Double.POSITIVE_INFINITY,它大於double表示的任何數字。你可以使用它作爲一個起點最少的搜索:

double minSalary = Double.POSITIVE_INFINITY; 
... 
if (minSal > emp.getSalary()) { 
    minSalary = emp.getSalary(); 
} 

另一種常見的伎倆是設置minSalary到列表的第一個元素,然後開始從第二個元素搜索。

+0

我如何去設置它到列表的第一個元素?我是這麼想的,但我不知道這麼做。 – user1869703 2013-04-25 02:02:49

+0

@ user1869703您可以在循環中執行,而不是在「addEmployee」中執行。但是,'POSITIVE_INFINITY'技巧應該可以工作。您也可以使用'Double'而不是'double',在這種情況下,您可以將'minSal'初始設置爲'null'。 – dasblinkenlight 2013-04-25 02:11:36

2
if (employees.isEmpty() { 
    return null; // No minimum salary available. 
} 
int minSalary = Integer.MAX_INT; 
for (Employee e : employees) { 
    minSalary = Math.min(minSalary, e.getSalary(); 
} 
return minSalary; 
0

下面是一個使用變化的Iterator

public double minSalary(List<Employee> employees) { 
    if (employees == null || employees.isEmpty()) { 
     throw new IllegalArgumentException(); 
    } 

    Iterator<Employee> iterator = employees.iterator(); 
    double min = iterator.next(); 
    while (iterator.hasNext()) { 
     min = Math.min(min, iterator.next().getSalary()); 
    } 

    return min; 
} 
+0

原始類型不能爲空。返回'Double.NaN'或-1可能會更好。 – ApproachingDarknessFish 2013-04-25 01:58:11

+0

你是對的,我更新它來拋出異常,但你的建議也很好。返回一個'Double'也可以工作,然後可以返回'null'。 – 2013-04-25 02:01:56

2

這聽起來像你想的最低工資爲每個部門的列表,它看起來像其他的答案只是給你跨部門的最低工資。如果我是正確的,要通過部門工資低,你可能只想通過列表循環,並把它們放在一個地圖的部門,像這樣:

public Map<String, Double> getLowSalaries(List<Employee> employees) { 
    Map<String, Double> lowSalaries = new HashMap<String, Double>(); 

    for(Employee employee : employees) { 
     Double lowSalaryForDept = lowSalaries.get(employee.getDept()); 

     if(lowSalaryForDept == null || lowSalaryForDept < employee.getSalary()) { 
      lowSalaries.put(employee.getDept(), employee.getSalary()); 
     } 
    } 
    return lowSalaries; 
} 
相關問題