【问题标题】:Organizing array list of objects JAVA组织对象的数组列表 JAVA
【发布时间】:2014-03-17 14:57:37
【问题描述】:

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

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

PW_1234,詹姆斯,邦德,01/02/10,1,10 PW_1235,约翰,布朗,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,马克,比克斯顿,05/13/11,2,13 PW_1242,莎拉,格洛弗,05/14/11,1,13.75 PW_1245,约翰,Doe,05/15/11,4,10.5 PW_1245,Mary,Doe,05/15/11,4,10.5 TL_1248,Abel,English,05/16/11,3,16.5,0.01,100,89 TL_1251,Eustis,Clauser,05/17/11,2,16,0.02,100,9 SU_1254,Henry,Hollowman,05/18/11,1,40000,0.01 PW_1240,Luke,Sailor,01/22/12,3,14.5 PW_1243,简,贝克,01/23/12,2,14 PW_1243,简,贝克,01/23/12,2,14 TL_1246,David,Brief,01/24/12,1,14.75,0.01,100,57 PW_1246,大卫,多森,01/24/12,1,14.75 TL_1249,贝克,安德森,01/25/12,4,11.5,0.01,100,100 TL_1252,弗兰克,唐森,01/26/12,3,17.5,0.02,100,39 SU_1255,Issac,阿西莫夫,01/27/12,2,43000,0.02 SU_1256,Issac,Shoreman,01/28/12,3,39000,0.01 SU_1257,Issac,Roberts,01/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,Samual,Dempky,11/25/13,2,15,0.01,100,10 TL_1250,查理,博曼,11/26/13,1,15.75,0.01,100,50 TL_1253,George,Fritzmen,11/27/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;
}

**这里是员工数组的创建方式:

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

【问题讨论】:

  • 你输入了if(employees[i]substring(0,2).equals("SU"))。你的意思是if(employees[i].substring(0,2).equals("SU"))?注意点。
  • makeEmployeeList() 方法应该做什么?
  • 哇,你为什么要使用String?你想达到什么目标?
  • makeEmployeeList() 在 JOptionPane 中显示文件中的所有内容。
  • 究竟是什么问题?不知道怎么排序?你没有得到子字符串?还是什么?

标签: java arrays sorting methods


【解决方案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] subsrting 之后漏掉了一个点 由于 string 是一个不可变对象,我建议你使用 StringBuilder 及其 append 方法而不是 +=。并使用其 toString() 方法将 StringBuilder 转换为 String。您还需要覆盖员工的 toString 方法。

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

【讨论】:

    【解决方案2】:

    当你使用 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);
      }
    }
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-07
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2013-12-19
      • 1970-01-01
      相关资源
      最近更新 更多