Java:如何从控制语句中检索数据?

时间:2014-06-11 00:50:30

标签: java

我正在为java类创建一个员工时钟。我的计划的这一部分用于报告个人的时间,并报告所有员工的时间。我的代码适用于个人,但我无法将其转换为所有员工的工作。我应该尝试循环遍历整个文件并检索它吗?控制语句中的信息导致我出现问题。另外,仅查看两周时间,使用日历和日期-14天是否是实现这一目标的好方法?

有关如何继续欣赏的任何反馈意见。

package PunchinPunchout;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;

public class IDchecker {

    private static BufferedReader br;
    private static BufferedReader br1;
    static int total;
    static int total1;


    public static void main(String args[]) throws IOException {

        getsubject();

    }

    public static void getsubject() throws FileNotFoundException, IOException {

        ArrayList<Integer> totalhours = new ArrayList<>();
        br = new BufferedReader(new FileReader("timeclock1.txt"));
        br1 = new BufferedReader(new FileReader("newemployee8.txt"));


        String line = "";
        String line1 = "";

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter an employee ID number: ");
        String idnumber = sc.next();//read the choice
        sc.nextLine();// discard any other data entered on the line

        while ((line1 = br1.readLine()) != null) {

            if (line1.contains(idnumber)) {

                System.out.println("Employee Name & ID ");
                System.out.println(line1);
            }

        }

        while ((line = br.readLine()) != null) {

            if (line.contains(idnumber + " ") && line.contains("in")) {
                System.out.println();
                System.out.println("  Date     Time         ID    Punched");
                System.out.println(line);

                String regexp = "[\\s:\\n]+"; // these are my delimiters
                String[] tokens; // here i will save tokens

                for (int i = 0; i < 1; i++) {
                    tokens = line.split(regexp);
                    total = Integer.parseInt(tokens[1]);

                }

            } else if (line.contains(idnumber + " ") && line.contains("out")) {

                System.out.println(line);

                String regexp = "[\\s:\\n]+";
                String[] tokens; 

                for (int i = 0; i < 1; i++) {


                    tokens = line.split(regexp); 
                    total1 = Integer.parseInt(tokens[1]);

                    System.out.print("Total hours for " + tokens[0] + " are: ");
                }

                int dailytotal = total1 - total;
                System.out.println(dailytotal + " hours"); 
                totalhours.add(dailytotal);

            }

        }
        System.out.println();
        int sum = totalhours.stream().mapToInt(Integer::intValue).sum();
        System.out.println("The total hours for the last two weeks is " + sum + " hours.");

    }
}

*来自timeclock1.txt的输出

  

05/05/2014 05:00:00 508 in

     

05/05/2014 09:00:00 508 out

     

05/05/2014 03:00:00 509 in

     

05/05/2014 09:00:00 509 out

     

05/05/2014 03:00:00 510 in

     

05/05/2014 08:00:00 510 out

     

05/05/2014 08:00:00 511 in

     

05/05/2014 10:00:00 511 out

*来自newemployee8.txt的输出

  詹姆斯布什10

     

bobby bush 11

     

john hunt 12

     

mick jag 13

     

jacob sanchez 14

1 个答案:

答案 0 :(得分:1)

好的,这只是一个顶级的例子,但它强调了像Java这样的OO语言的强大功能......

根据您的要求,可以通过多种方式实现这一目标。我已经做了一些假设(比如in后跟同一个雇员的out,但是基本的要点已经证明了。

目的是将一些功能集中到可重用和可管理的块中,从而减少代码重复。简化了对数据的访问,因为它在内存中完成,速度更快......

首先,您需要创建员工和时钟数据的对象表示,这样可以更轻松地管理...

员工示例

public class Employee {

    private final int id;
    private final String name;

    public Employee(String text) {
        String[] parts = text.split(" ");
        id = Integer.parseInt(parts[2]);
        name = parts[0] + " " + parts[1];
    }

    public String getName() {
        return name;
    }

    public int getId() {
        return id;
    }

}

TimeClockEntry示例

public class TimeClockEntry {

    private Date inTime;
    private Date outTime;
    private int employeeID;

    public TimeClockEntry(String text) throws ParseException {
        String parts[] = text.split(" ");
        employeeID = Integer.parseInt(parts[2]);
        setClockTimeFrom(text);
    }

    public void setClockTimeFrom(String text) throws ParseException {
        String parts[] = text.split(" ");
        if ("in".equalsIgnoreCase(parts[3])) {
            inTime = CLOCK_DATE_TIME_FORMAT.parse(parts[0] + " " + parts[1]);
        } else if ("out".equalsIgnoreCase(parts[3])) {
            outTime = CLOCK_DATE_TIME_FORMAT.parse(parts[0] + " " + parts[1]);
        }
    }

    public int getEmployeeID() {
        return employeeID;
    }

    public Date getInTime() {
        return inTime;
    }

    public Date getOutTime() {
        return outTime;
    }

}

现在,我们需要某种“管理器”来管理这两个类的细节,这些管理器应该提供允许用来检索它们管理的信息的访问方法。这些经理还将负责从文件中加载数据......

EmployeeManager示例

public class EmployeeManager {

    private Map<Integer, Employee> employees;

    public EmployeeManager() throws IOException {
        employees = new HashMap<>(25);
        try (BufferedReader br = new BufferedReader(new FileReader(new File("NewEmployee8.txt")))) {
            String text = null;
            while ((text = br.readLine()) != null) {
                Employee emp = new Employee(text);
                employees.put(emp.getId(), emp);
            }
        }
    }

    public List<Employee> getEmployees() {
        return Collections.unmodifiableList(new ArrayList<Employee>(employees.values()));
    }

    public Employee getEmployee(int id) {
        return employees.get(id);
    }

}

TimeClockManager示例

public class TimeClockManager {

    private Map<Integer, List<TimeClockEntry>> timeClockEntries;

    public TimeClockManager() throws IOException, ParseException {
        timeClockEntries = new HashMap<>(25);
        try (BufferedReader br = new BufferedReader(new FileReader(new File("TimeClock1.txt")))) {
            String text = null;
            TimeClockEntry entry = null;
            int line = 0;
            while ((text = br.readLine()) != null) {

                if (line % 2 == 0) {
                    entry = new TimeClockEntry(text);
                } else {
                    entry.setClockTimeFrom(text);

                    List<TimeClockEntry> empEntries = timeClockEntries.get(entry.getEmployeeID());
                    if (empEntries == null) {
                        empEntries = new ArrayList<>(25);
                        timeClockEntries.put(entry.getEmployeeID(), empEntries);
                    }

                    empEntries.add(entry);

                }
                line++;

            }
        }
    }

    public List<TimeClockEntry> getByEmployee(Employee emp) {

        List<TimeClockEntry> list = timeClockEntries.get(emp.getId());
        list = list == null ? new ArrayList<>() : list;
        return Collections.unmodifiableList(list);

    }

}

现在,在内部,这些经理通过使用Map来管理数据,以便更容易找到数据,具体而言,这最关键的是员工的身份

现在,一旦我们拥有了这些,我们可以随时向您索取信息......

public Report() {
    try {
        EmployeeManager empManager = new EmployeeManager();
        TimeClockManager timeClockManager = new TimeClockManager();

        for (Employee emp : empManager.getEmployees()) {

            System.out.println("[" + emp.getId() + "] " + emp.getName());
            for (TimeClockEntry tce : timeClockManager.getByEmployee(emp)) {
                System.out.println("    "
                        + CLOCK_DATE_TIME_FORMAT.format(tce.getInTime())
                        + " to "
                        + CLOCK_DATE_TIME_FORMAT.format(tce.getOutTime()));
            }

        }

    } catch (IOException | ParseException exp) {
        exp.printStackTrace();
    }
}

另一种方法是将两个经理合并为一个班级。基本的想法是加载员工和时钟数据,时钟数据将成为Employee的属性,您可以直接访问它。

这是一个稍微优雅的解决方案,因为您将所有数据包含在单个构造中,但可能无法满足您的需求

完全可运行的示例

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import oracle.jrockit.jfr.parser.ParseException;

public class Report {

    public static void main(String[] args) {
        new Report();
    }

    public Report() {
        try {
            EmployeeManager empManager = new EmployeeManager();
            TimeClockManager timeClockManager = new TimeClockManager();

            for (Employee emp : empManager.getEmployees()) {

                System.out.println("[" + emp.getId() + "] " + emp.getName());
                for (TimeClockEntry tce : timeClockManager.getByEmployee(emp)) {
                    System.out.println("    "
                            + CLOCK_DATE_TIME_FORMAT.format(tce.getInTime())
                            + " to "
                            + CLOCK_DATE_TIME_FORMAT.format(tce.getOutTime()));
                }

            }

        } catch (IOException | ParseException exp) {
            exp.printStackTrace();
        }
    }

    public class EmployeeManager {

        private Map<Integer, Employee> employees;

        public EmployeeManager() throws IOException {
            employees = new HashMap<>(25);
            try (BufferedReader br = new BufferedReader(new FileReader(new File("NewEmployee8.txt")))) {
                String text = null;
                while ((text = br.readLine()) != null) {
                    if (!text.trim().isEmpty()) {
                        Employee emp = new Employee(text);
                        employees.put(emp.getId(), emp);
                    }
                }
            }
        }

        public List<Employee> getEmployees() {
            return Collections.unmodifiableList(new ArrayList<Employee>(employees.values()));
        }

        public Employee getEmployee(int id) {
            return employees.get(id);
        }

    }

    public class TimeClockManager {

        private Map<Integer, List<TimeClockEntry>> timeClockEntries;

        public TimeClockManager() throws IOException, ParseException {
            timeClockEntries = new HashMap<>(25);
            try (BufferedReader br = new BufferedReader(new FileReader(new File("TimeClock1.txt")))) {
                String text = null;
                TimeClockEntry entry = null;
                int line = 0;
                while ((text = br.readLine()) != null) {

                    if (!text.trim().isEmpty()) {
                        if (line % 2 == 0) {
                            entry = new TimeClockEntry(text);
                        } else {
                            entry.setClockTimeFrom(text);

                            List<TimeClockEntry> empEntries = timeClockEntries.get(entry.getEmployeeID());
                            if (empEntries == null) {
                                empEntries = new ArrayList<>(25);
                                timeClockEntries.put(entry.getEmployeeID(), empEntries);
                            }

                            empEntries.add(entry);

                        }
                        line++;
                    }

                }
            }
        }

        public List<TimeClockEntry> getByEmployee(Employee emp) {

            List<TimeClockEntry> list = timeClockEntries.get(emp.getId());

            list = list == null ? new ArrayList<>() : list;

            return Collections.unmodifiableList(list);

        }

    }

    public class Employee {

        private final int id;
        private final String name;

        public Employee(String text) {
            System.out.println("[" + text + "]");
            for (char c : text.toCharArray()) {
                System.out.print((int) c + ",");
            }
            System.out.println("");
            String[] parts = text.split("\\s+");
            id = Integer.parseInt(parts[2]);
            name = parts[0] + " " + parts[1];
        }

        public String getName() {
            return name;
        }

        public int getId() {
            return id;
        }

    }

    public static final SimpleDateFormat CLOCK_DATE_TIME_FORMAT = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    public static final SimpleDateFormat CLOCK_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");

    public class TimeClockEntry {

        private Date inTime;
        private Date outTime;
        private int employeeID;

        public TimeClockEntry(String text) throws ParseException {
            System.out.println("[" + text + "]");
            for (char c : text.toCharArray()) {
                System.out.print((int) c + ",");
            }
            System.out.println("");
            String parts[] = text.split("\\s+");
            employeeID = Integer.parseInt(parts[2]);
            setClockTimeFrom(text);
        }

        public void setClockTimeFrom(String text) throws ParseException {
            String parts[] = text.split("\\s+");
            if ("in".equalsIgnoreCase(parts[3])) {
                inTime = CLOCK_DATE_TIME_FORMAT.parse(parts[0] + " " + parts[1]);
            } else if ("out".equalsIgnoreCase(parts[3])) {
                outTime = CLOCK_DATE_TIME_FORMAT.parse(parts[0] + " " + parts[1]);
            }
        }

        public int getEmployeeID() {
            return employeeID;
        }

        public Date getInTime() {
            return inTime;
        }

        public Date getOutTime() {
            return outTime;
        }

    }

}