组织JAVA对象的数组列表

时间:2014-02-18 03:43:19

标签: java arrays sorting methods

我在组织员工名单时遇到了麻烦。我只需要根据他们的员工类型(前两个字母)来组织它们。每个对象都以员工代码开头,这是前两个字母。这是我需要分离位置类型但由于某种原因我无法抓住它们。

这是我创建对象并将其存储在数组中的文件。

  

PW_1234,James,Bond,01/02 / 10,1,10 PW_1235,John,Brown,02/03 / 10,2,10.5   PW_1236,霍华德,约翰逊03/04 / 10,3,11   PW_1237,弗朗西斯,Themule,04/05 / 11,4,10.75   PW_1238,马修,刘易斯,05/06 / 11,1,12.75   PW_1239,马克,Bixton,05/13 / 11,2,13   PW_1242,Sarah,Glover,05/14 / 11,1,13.75 PW_1245,John,Doe,05/15 / 11,4,10.5   PW_1245,玛丽,能源部,05/15 / 11,4,10.5   TL_1248,阿贝尔,英语,05/16 / 11,3,16.5,0.01,100,89   TL_1251,Eustis的,克劳泽,05/17 / 11,2,16,0.02,100,9   SU_1254,亨利,Hollowman,05/18 / 11,1,40000,0.01   PW_1240,Luke,Sailor,01/22 / 12,3,14.5 PW_1243,Jane,Baker,01/23 / 12,2,14   PW_1243,简,贝克,01/23 / 12,2,14   TL_1246,大卫,简要,01/24 / 12,1,14.75,0.01,100,57   PW_1246,大卫,Doson,01/24 / 12,1,14.75   TL_1249,贝克,安德森,01/25 / 12,4,11.5,0.01,100,100   TL_1252,弗兰克,DONSON,1月26日/ 12,3,17.5,0.02,100,39   SU_1255,艾萨克阿西莫夫,1月27日/ 12,2,43000,0.02   SU_1256,伊萨克,Shoreman,01/28 / 12,3,39000,0.01   SU_1257,伊萨克,罗伯茨,1月29日/ 12,4,35500,0.01   PW_1241,John,Candy,11/23 / 13,4,9.5 PW_1244,Kate,Smith,11/24 / 13,3,15.5   PW_1244,凯特,手柄11/24 / 13,3,15.5   TL_1247,塞穆尔,Dempky 11/25 / 13,2,15,0.01,100,10   TL_1250,查理,博曼,26分之11/ 13,1,15.75,0.01,100,50   TL_1253,乔治,Fritzmen,27分之11/ 13,4,12.5,0.02,100,27

以下是代码:

private String makeEmployeeList()
{
    String list = "";

    for(int i=0; i < employees.length; i++)
    {
        list += "\n"+employees[i].toString();
        if(employees[i]substring(0,2).equals("SU"))
        {
            list += "\n"+employees[i].toString();
        }
    }
    return list;
}

**以下是employees数组的创建方式:

private Employee[] employees;

**以下是所有内容的加载方式。

public void loadEmployeesFromFile(String fileName)
            {
               File inFile = new File(fileName);
               if(inFile.exists())  //  MAKE SURE FILE EXISTS
               {    
                   try
                   {
                       BufferedReader inReader = new BufferedReader(new FileReader(inFile));
                      inReader.mark(32000);
                       String inLine = inReader.readLine();

                       //************************************
                       //  Counting rows to set array size
                       //************************************

                       int rowCount = 0;
                       while (inLine != null  && !inLine.equals(""))
                       {
                            rowCount++;
                           inLine = inReader.readLine();
                       }
                       inReader.reset();

                       //*******************
                       // re-reading data 
                       //*******************
                       this.employees = new Employee[rowCount];

                       for(int rowIndex = 0;rowIndex < rowCount; rowIndex++)
                       {
                            inLine = inReader.readLine();
                            Scanner employeeScanner = new Scanner(inLine).useDelimiter(",");
                            String workerType = employeeScanner.next();
                            String firstName = employeeScanner.next();
                            String lastName = employeeScanner.next();
                            String hireDate = employeeScanner.next();
                            int shift = employeeScanner.nextInt();

                            if(workerType.substring(0,2).equals("PW"))
                            {
                                double pay = employeeScanner.nextDouble();  
                                employees[rowIndex]= new ProductionWorker(workerType, firstName, lastName, hireDate, shift, pay);      
                            } 
                            else if(workerType.substring(0,2).equals("TL"))
                            {
                                double pay = employeeScanner.nextDouble();
                                double bonusRate = employeeScanner.nextDouble();
                                int reqHours = employeeScanner.nextInt();
                                int recHours = employeeScanner.nextInt();
                                employees[rowIndex]= new TeamLeader(workerType, firstName, lastName, hireDate, shift, pay, bonusRate, reqHours, recHours);      
                            } 
                            else if(workerType.substring(0,2).equals("SU"))
                            {
                                double salary = employeeScanner.nextDouble();
                                double bonusRate = employeeScanner.nextDouble();
                                employees[rowIndex]= new ShiftSupervisor(workerType, firstName, lastName, hireDate, shift, salary, bonusRate ); 
                            } 
                       }
                       return;
                   }catch(IOException ioe)
                   {
                       System.err.print("\nTrouble reading employee file: "+fileName);
                   }
               }
               JOptionPane.showMessageDialog(null, "\nFile Name does not exist!\n Process terminating!");
               System.exit(0);
            }

2 个答案:

答案 0 :(得分:1)

private String makeEmployeeList(){ 
StringBuilder sbSU = null;

for(int i=0; i < employees.length; i++)
{
    sbSU = new StringBuilder();
    if(employees[i].substring(0,2).equals("SU"))
    {
        sbSU.append(employees[i].toString());
    }
}
return sbSU.toString();
}

首先,你在emplyees [i]改编后错过了一个点 由于string是一个不可变对象,我建议你使用StringBuilder及其append方法而不是+ =。并使用其toString()方法将StringBuilder转换为String。您还需要覆盖Employees的toString方法。

要对数组中的员工进行排序,您需要实现Comparable或Comparator接口,以便Array在排序员工时知道要使用哪些条件,在您的情况下是比较员工的类型

答案 1 :(得分:1)

当您使用JOptionPane时,您可以使用内部的html来为其提供格式。创建一个Employee类并按类型进行自然顺序,或者如果您不想使用Comparable

,则可以使用Comparator

我为你做了一个完整的例子。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.swing.JOptionPane;

public class Employee implements Comparable<Employee> {
    private String type;
    private String name;

    public Employee(String type, String name) {
        super();
        this.type = type;
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + ((type == null) ? 0 : type.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Employee other = (Employee) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (type == null) {
            if (other.type != null)
                return false;
        } else if (!type.equals(other.type))
            return false;
        return true;
    }

    public int compareTo(Employee o) {
        if (this.type.equals(o.type)) {
            return name.compareTo(o.name);
        }
        return type.compareTo(o.type);
    }

    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<Employee>();
        employees.add(new Employee("CA","John"));
        employees.add(new Employee("CA", "Suzy"));
        employees.add(new Employee("TA","Malcom"));
        employees.add(new Employee("AA","Rose"));

        // Sort the list by type as its natural order or use proper Comparator
        Collections.sort(employees);

        StringBuilder sb = new StringBuilder();
        sb.append("<html><table><tr><td>Type</td><td>Name</td></tr>");
        for (Employee e : employees) {
            sb.append("<tr>");
            sb.append("<td> ").append(e.getType()).append("</td>");
            sb.append("<td> ").append(e.getName()).append("</td>");
            sb.append("</tr>");
        }
        sb.append("</table></html>");
        JOptionPane.showMessageDialog(null, sb);
  }
}

输出:

enter image description here