静态员工编号,文件处理问题

Static Employee number, file handling issue

我的员工编号静态变量在处理文件时遇到问题。当我创建一个新员工时,我会自动按顺序获取下一个数字。但是当我重新启动程序并尝试创建一个新的员工时,员工编号恢复为 1。

有没有任何人可能会建议阅读前任员工并从那里继续编号的方法?

提前感谢您的帮助!! :)

     @SuppressWarnings("serial")
public class Employee extends Person implements Serializable
{   
    private Date dateOfBirth; 
    private Date startDate;
    private double salary;
    private int employeeNumber;
    private static int nextEmployeeNumber = 1;  

    private final double MAX_SALARY = 70000;
    private final double INCREMENT = 250;


    public Employee()
    {
        super();
        dateOfBirth = new Date();
        startDate = new Date();
        salary = 0.0;
        employeeNumber = nextEmployeeNumber++;
    }



    public Employee(String title, String firstName, String surname, String     phoneNumber, 
                int day, int month, int year, int sD, int sM, int sY, double     salary)
    {
        super(title, firstName, surname, phoneNumber);
        this.dateOfBirth = new Date(day, month, year);
        this.startDate = new Date(sD, sM, sY);
        this.employeeNumber = employeeNumber++;
        this.salary = salary;
    }

    //Overrides the toString methods, providing its own implementation
    @Override
    public String toString()
    {
        return(super.toString() + "\nEmployee Number: " + employeeNumber +     "\nEmployee Salary: " + salary + 
                              "\nEmployee DOB: " + dateOfBirth + "\nEmployee     Start Date: " + startDate);
    }


    //Both .equals methods are usable. To save any possible conflicts as might occur 
    //in a larger system, I have set the equals method to call back to the Object class
    @Override
    public boolean equals(Object otherObject)
    {
        Employee other = (Employee) otherObject;
        if (otherObject == null)
        {
            return false;
        }

        if(getClass() != otherObject.getClass())
        {   
            return false;
        }

        if(super.name.equals(otherObject)&&
          (employeeNumber == other.employeeNumber)&&
          (dateOfBirth == other.dateOfBirth)&&
          (startDate == other.startDate)&&
          (salary == other.salary));
        {
           return true;
        }
    }

    int quit = 0;
    public void read()
    {   
        Scanner kbInt = new Scanner(System.in);
        Scanner kbString = new Scanner(System.in);



        System.out.print("\n\nEmployee Title: "); 
        name.title = kbString.nextLine();

        System.out.print("\nEmployee First Name: "); 
        name.firstName = kbString.nextLine();

        System.out.print("\nEmployee Surname: "); 
        name.surname = kbString.nextLine();

        System.out.print("\nEmployee DOB Day: "); 
        dateOfBirth.day = kbInt.nextInt();

        System.out.print("\nEmployee DOB Month: "); 
        dateOfBirth.month = kbInt.nextInt();

        System.out.print("\nEmployee DOB Year: "); 
        dateOfBirth.year = kbInt.nextInt();

        System.out.print("\nEmployee Phone Number: "); 
        phoneNumber = kbString.nextLine();

        System.out.print("\nEmployee Start Day: "); 
        startDate.day = kbString.nextInt();

        System.out.print("\nEmployee Start Month: "); 
        startDate.month = kbString.nextInt();

        System.out.print("\nEmployee Start Year: "); 
        startDate.year = kbString.nextInt();

        System.out.print("\nEmployee Salary: "); 
        salary = kbInt.nextDouble();
    }



    //Getters & Setters of DOB, start date, employee number & salary
    public Date getDateOfBirth() 
    {
        return dateOfBirth;
    }

    public void setStartDate(Date startDate) 
    {
        this.startDate = startDate;
    }

    public Date getstartDate() 
    {
        return startDate;
    }

    public void setDateOfBirth(Date dateOfBirth) 
    {
         this.dateOfBirth = dateOfBirth;

    }

    public int getEmployeeNumber() 
    {
        return employeeNumber;
    }

    public double getSalary() 
    {
        return salary;
    }

    public void setSalary(double salary) throws IllegalArgumentException
    {
        this.salary = salary;
        if(salary < 0 || salary > 70000)
        throw new IllegalArgumentException("Enter Valid Salary");
    }

    public void incrementSalary()
    {
        if(salary + INCREMENT <= MAX_SALARY)
            salary += INCREMENT;
        else
            salary = MAX_SALARY;
    }       
 }


     import java.util.*;
           import java.io.*;
           import java.nio.file.*;

           /**
            * Class B.Sc. CSDF
            * Instructor Maria Boyle
            * Description: EmployeeMenu class for Hotel application
            * Date: 01/11/2015
            * @author Mark Melling
            * @version 1.0
            */

            ////////////////////////////////////////////////////////////////////////
            //   This class contains an ArrayList, and the methods for modifying  //
            //   the ArrayList as required, as well as the methods for serializing//
            //   and deserializing the ArrayList                                  //
            ////////////////////////////////////////////////////////////////////////

           @SuppressWarnings("serial")
           public class EmployeeFileHandler_1 implements Serializable
           {
            //Declare ArrayList called employees - for storing a list of Employees
            private ArrayList<Employee> employees;
            private Scanner keyIn = new Scanner(System.in);

            public EmployeeFileHandler_1()              // Default Constructor
            {
                employees = new ArrayList<Employee>();  // Construct Employee ArrayList
            }


            //////////////////////////////////////////////////////
            // Method Name : add()                              //
            // Return Type : void                               //
            // Parameters : None                                //
            // Purpose: Reads one Employee record from the user //
            //        and adds it to the ArrayList employeeList //
            //////////////////////////////////////////////////////  

            public void add()
            {
                Employee employee = new Employee();         // Create a Employee object

                employee.read();                            // Read its details 
                employees.add(employee);                    // Add it to the employeeList
            }

            //////////////////////////////////////////////////////
            // Method Name : list()                             //
            // Return Type : void                               //
            // Parameters : None                                //
            // Purpose: Loops around the ArrayList employeeList //
            //          and prints to screen employee details   //
            //////////////////////////////////////////////////////

            public void list() 
            {
                for(Employee currentEmployee : employees)
                {
                    System.out.println(currentEmployee);        
                }       
            }

            //////////////////////////////////////////////////////
            // Method Name: view()                              //
            // Return Type: void                                //
            // Parameters:  None                                //
            // Purpose:     View Employee record from the       //
            //              ArrayList employeeList              //
            //////////////////////////////////////////////////////  

            public void view() 
            {
                //Read the number of the Employee to be viewed
                System.out.println("\nEnter Employee Number:");
                int employeeToView = keyIn.nextInt();

                //Read every Employee object in videos
                for(Employee currentEmployee : employees)
                {
                    // If it's number equals the number of the Employee to view
                    if(currentEmployee.getEmployeeNumber() == employeeToView)
                    {
                        //Display Employee
                        System.out.println(currentEmployee);
                        break;
                    }
                }   
            }

            ////////////////////////////////////////////////////////
            // Method Name: delete()                              //
            // Return Type: void                                  //
            // Parameters:  None                                  //
            // Purpose:     Reads Employee record from the        //
            //              ArrayList employeeList & deletes user //
            ////////////////////////////////////////////////////////

            public void delete()
            {
                //Read the number of the video to be deleted from the user
                System.out.println("Enter Number of Employee To Delete");
                int employeeToDelete = keyIn.nextInt();

                //for every Video object in videos
                for(Employee currentEmployee : employees)
                {
                    //if it's number equals the number of the Video to view
                    if(currentEmployee.getEmployeeNumber() == employeeToDelete)
                    {
                        //display it
                        System.out.println(currentEmployee);

                        //Remove it from videos
                        employees.remove(currentEmployee);
                        break;
                    }
                }
            }


            ////////////////////////////////////////////////////////
            // Method Name: delete()                              //
            // Return Type: void                                  //
            // Parameters:  None                                  //
            // Purpose:     Reads Employee record from the        //
            //              ArrayList employeeList & edits user   //
            ////////////////////////////////////////////////////////

            public void edit()
            {
                //Read the number of the employee to be edited from the user
                System.out.println("Enter number of Employee to edit");
                int employeeToEdit = keyIn.nextInt();

                //for every Employee object in employees
                for(Employee currentEmployee : employees)
                {
                    //if it's number equals the number of the employee to view
                    if(currentEmployee.getEmployeeNumber() == employeeToEdit)
                    {
                        //Display employee
                        System.out.println(currentEmployee);

                        //get it's index
                        int index = employees.indexOf(currentEmployee);

                        //read in a new employee
                        currentEmployee.read();

                        //reset the object in employees
                        employees.set(index, currentEmployee);
                        break;
                    }
                }
            }

            ///////////////////////////////////////////////////////
            // Method Name : writeRecordsToFile()                //
            // Return Type : void                                //
            // Parameters : None                                 //
            // Purpose: Writes the ArrayList employees to the    //
            //          file employees.bin before closing it     //
            /////////////////////////////////////////////////////// 

            public void writeRecordsToFile()
            {
                if(employees instanceof Serializable)
                try
                {
                    // Serialize the ArrayList...
                    FileOutputStream fileStream = new FileOutputStream("employees.bin");

                    ObjectOutputStream os = new ObjectOutputStream(fileStream);

                    os.writeObject(employees);

                    os.close();
                }
                catch(FileNotFoundException fNFE)
                {
                    System.out.println("Cannot create file to store employees.");
                }
                catch(Exception e)
                {
                    System.out.println("Input Output Error" + e.getMessage());
                }
            }   

            //////////////////////////////////////////////////////////
            // Method Name: readRecordsToFile()                     //
            // Return Type: void                                    //
            // Parameters:  None                                    //
            // Purpose:     Reads the ArrayList employees from the  //
            //              file employees.bin, uses the Path.get   //
            //              method to test whether the path to the  //
            //              file exists & adds error handling.      //          
            //////////////////////////////////////////////////////////

            @SuppressWarnings("unchecked")
            public void readRecordsFromFile()
            {
                if(employees instanceof Serializable)
                try
                {
                    final String FILENAME = "employees.bin";
                    Path p = Paths.get(FILENAME);

                    if(Files.exists(p))
                    {
                        //Creates Object
                        FileInputStream inputStream = new FileInputStream(p.toString());
                        ObjectInputStream is = new ObjectInputStream(inputStream);

                        Object o = is.readObject();             //READ an Object from the file
                        if(o instanceof ArrayList)              //IF Object is an ArrayList
                        employees = (ArrayList<Employee>)o;     //ASSIGN Object to employees
                        is.close(); 
                    }
                    else    
                    {
                        System.out.println("File "+p.getFileName() + "Doesnt exist");
                    }       
                }
                catch(FileNotFoundException fNFE)
                {
                    System.out.println("File not found " + fNFE.getMessage());
                }
                catch(IOException iOE)
                {
                    System.out.println("Input output error " + iOE.getMessage());
                }
                catch(Exception e)
                {
                    System.out.println(e.getMessage());
                }
            }
           }

你需要 serialise/persist 为此你的数据。这可以通过将数据写入文件、使用数据库或其他方法来完成。

然后您可以从 database/file 中读取您的数据以检索所有持久条目并找出下一个员工编号。

** 编辑 ** 你编辑了我的答案而不是发布它