2014-02-18 5 views
1

У меня возникли проблемы с организацией списка моих сотрудников. Мне просто нужно организовать их в соответствии с их типом работника (первые две буквы). Каждый объект начинается с кода сотрудника, который является первыми двумя буквами. Это то, что мне нужно, чтобы разделить типы позиций, но по какой-то причине я не могу их захватить.Организация списка массивов объектов JAVA

Вот файл, из которого я создаю объекты и храня их в массивах.

PW_1234, Джеймс Бонд, 01/02/10,1,10 PW_1235, Джон Браун, 02/03/10,2,10.5 PW_1236, Говард Джонсон, 03/04/10,3 , 11 PW_1237, Francis, Themule, 04/05/11,4,10.75 PW_1238, Mathew, Lewis, 05/06/11,1,12.75 PW_1239, Mark, 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, Mary, Doe, 05/15/11,4,10.5 TL_1248, Abel, английский, 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, Jane, Baker, 01/23/12,2,14 PW_1243, Jane, Baker, 01/23/12,2,14 TL_1246, David, Brief, 01/24/12,1,14.75,0.01, 100,57 PW_1246, David, Doson, 01/24/12,1,14,75 TL_1249, Baker, Anderson, 01/25/12,4,11.5,0.01,100,100 TL_1252, Frank, Donson, 01/26/12,3,17,5,0,02,100,39 SU_1255, Issac, Asimov, 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, Kate , Ручка, 11/24/13,3,15,5 TL_1247, Samual, Dempky, 11/25/13,2,15,0.01,100,10 TL_1250, Charley, Boman, 11/26/13,1,15.75 , 0,01 100,50 TL_1253, Джордж, 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); 
      } 
+1

Вы помещаете 'если (сотрудники [я] подстроки (0,2) .equals ("SU"))'. Вы имели в виду 'if (employees [i] .substring (0,2) .equals (" SU "))'? Обратите внимание на точку. – einnocent

+1

Что должен делать метод 'makeEmployeeList()'? –

+0

Вау, почему вы используете 'String'? Чего вы хотите достичь? – nachokk

ответ

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

Прежде всего, вы пропустили точку после [я работников фирмы] subsrting В строке непреложный объект, я предлагаю вам использовать StringBuilder и его метод на добавлении вместо + =. и использовать его метод toString() для преобразования StringBuilder в String. Вам также необходимо переопределить метод toString ваших сотрудников.

для сортировки сотрудников в массиве, вам нужно реализует Сопоставимые или компаратор интерфейс, так что массив знает, какие критерии использовать при сортировке ваших сотрудников, в вашем случае это сравнить Типу работника

1

Как вам используют JOptionPane, вы можете использовать html внутри, чтобы придать ему формат. Сделайте класс Employee и сделайте его естественным, по типу, или вы можете использовать компаратор, если вы не хотите использовать Comparable

Я сделал вам полный пример.

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

Смежные вопросы