Welcome to Dream.In.Code
Getting Java Help is Easy!

Join 132,639 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,080 people online right now. Registration is fast and FREE... Join Now!




Using an ArrayList of objects with File IO

 
Reply to this topicStart new topic

Using an ArrayList of objects with File IO, Need some help with conceptual design

Gerbilkit
post 11 Oct, 2008 - 07:08 PM
Post #1


New D.I.C Head

*
Joined: 1 Oct, 2008
Posts: 14

I'm not asking anyone to write my code for me, I do need some help with deciding which classes and methods to use however. I am working on a project that requires the main system, EmployeeSystem to be able to open a file with JFileChooser, and then write to that file, run a payroll system on it, and search it for a particular employee using a directory system. The directory system code actually exists from a previous project, and is designed to work with an array. The problem is that the file I am working with has two different employee classes, FullTime and Casual. My solution at the moment is to use an ArrayList. Which I believe is not only able to expand it's size when necessary, but can actually store more than one class of object.

So my question is what file IO class/method would I use to read this file and determine what the first character is. (to determine what class of object to cast it to), and then to break up all the rest of the variables so I can add them to the ArrayList. The file contains a new object on each line, and each variable is separated by a space. The first variable is a single number, either 1 or 2, 1 means Casual Employee, and 2 means FullTime Employee.

The EmployeeSystem creates a file object and associates it with a file using JFileChooser, and then I plan to run the directory system on that file object, and create the ArrayList in the directory system, and as soon as the array list is created, the original code should work with only minor tweaks. I believe this method is sound, but I am not positive that it will work.

My big question though is what class/method will allow me to obtain the variables from each line in the file so that I can convert them into objects for the ArrayList.

Here is the file Employees.txt
CODE

2 Jeffery Johnson A001 06/14/1978 08/01/2006 402-486-5104 Lincoln NE 68588 1400
1 Jeffery Smith B002 09/12/1973 01/03/1999 402-357-5104 Seward NE 68801 3 15
2 Jessica Smith A303 11/21/1974 02/14/2003 402-408-6693 Eagle NE 68347 2200
2 Jeremy Suing X001 06/05/1975 05/16/2005 402-472-1658 Lincoln NE 68588 50
1 Sally Smith B001 01/11/1980 08/01/2006 402-357-3798 Fremont NE 68321 9 14
2 John Johnson B010 06/14/1979 08/01/2000 402-486-5110 Lincoln NE 68588 1450
1 Sarah Smith B200 10/14/1974 01/31/1997 402-408-5104 Utica NE 68701 5 25
1 John Doe A678 03/28/1981 03/02/1998 303-804-1169 Littleton CO 80104 4 10
1 Tad Jacobs X222 07/01/1975 08/16/2003 719-555-5555 Denver CO 80237 7 13
2 Ella Roberts B501 09/04/1983 05/10/2006 402-472-1100 Lincoln NE 68521 2400
1 Ellen Smith A501 08/24/1982 03/19/2001 402-472-2200 Lincoln NE 68520 3 40
2 Bobby Smith B555 12/04/1983 10/10/2006 402-470-1200 Lincoln NE 68527 240
User is offlineProfile CardPM

Go to the top of the page

pbl
post 11 Oct, 2008 - 07:27 PM
Post #2


D.I.C Lover

Group Icon
Joined: 6 Mar, 2008
Posts: 2,982



Thanked 190 times

Dream Kudos: 75
My Contributions


OK
you can make a class Employee

and then derive 2 classes from it

CasualEmployee and RegularEmployee

The class Employee will have the common fields: name, date, sin, ... actually all fields

You create your ArrayList as an ArrayList of Employee

You read the file and depending of the first digit you build a CasualEmployee or a RegularEmployee and add it the ArrayList

CODE

Employee x;
if(firstDigit == '1')
   x = new RegularEmployee(name, sin, date,....
else
  x = new CasualEmployee(name, sin, date, ....
arrayList.add(x);


When you'll read back from the arrayList you can use the instanceof operator to know from which type the employee is

CODE

for(Employe e : arrayList) {
   if(e instanceof CasualEmployee) {
   .....
  }
  else {
  ......        // assume RegularEmployee
  }
}

User is offlineProfile CardPM

Go to the top of the page

Gerbilkit
post 12 Oct, 2008 - 01:58 PM
Post #3


New D.I.C Head

*
Joined: 1 Oct, 2008
Posts: 14

So an ArrayList requires a superclass in order to be defined and used? I suppose that makes sense, and it certainly seems like a more elegant solution as there is a lot of redundancy as of now between FullTime and Casual employee classes. In that case how do you derive a class from another class? I would assume that the Employee class would contain most of the basic data, and the other classes would only contain their specific variables. Is it just a different way of declaring the sub classes in opening declaration? I don't think I've ever done anything like this before.

Thanks again. If you wanted this is the code for the two classes, but that shouldn't matter as to the generic question of how to derive a class from another class using inheritance.


Nevermind found it, working on coding the superclass now. I think I can figure the rest out now. Thanks for your time. biggrin.gif


FullTimeEmployee
CODE

/*
* FullTimeEmployee.java
*
* CSCE 155 Fall 2008
* Assignment 2
* @author Jared Wiebelhaus
* @version
*/

// import statements
import java.util.*;

public class FullTimeEmployee {

    //------------------Declare Constants---------------------------------------
    
    /**
     * Represents the percentage of the federal tax
     */
    private final double FEDERAL_TAX_PERCENT = 0.15;
    
    /**
     * Represents the percentage of the health insurance deduction
     */
    private final double HEALTH_INSURANCE_PERCENT = 0.05;  

    /**
     * Represents the percentage of the Retirement Savings deduction
     */
    private final double RETIREMENT_SAVINGS_PERCENT = 0.12;  

    /**
     * Represents the percentage of the state tax
     */
    private final double STATE_TAX_PERCENT = 0.08;  
    
    //-------------Declare private variables-----------------------------------
    
    /**
     *variables used to hold the values for various information
      *about the employee including name, ID, phone number, street address,
      *city, state, and zip code
     */
    private String     employeeName;     
     private String    employeeID;
     private String phoneNumber;
     private String streetAddress;
     private String city;
     private String state;
     private String zip;
     private double netPay;
    
    /**
     * Represents the amount in dollars of the salary for the employee
     */
    private int     monthlySalary;     
    /**
     * Represents the date of employment
     */
    private GregorianCalendar     startDate;
     /**
     * Represents the birth date for the employee
     */        
     private GregorianCalendar        dateOfBirth;
     /**
     * Various variables used to calculate pay deductions for the method
     *calculateNetMonthly() used to calculate net pay for the employee
     */
           private double deductionFederalTax;
          private double deductionStateTax;
          private double deductionRetirement;
          private double deductionHealth;
          private double totalDeduction;
        
    /**
     * Constructor used to create this object.  Responsible for setting
     * all of this object's information to their corresponding default values
     */
    public FullTimeEmployee(){
        this.employeeName = "";
        this.employeeID = "";
          this.phoneNumber = "";
          this.streetAddress = "";
          this.city = "";
          this.state = "";
          this.zip = "";
    }//end of constructor
    
    /**
     * Returns the employee's name from this object
     * @return <code>String</code> Name of the Employee represented in object
     */
    public String getEmployeeName() {
        return employeeName;
    }
     /**
     * Returns the employee's ID from this object
     * @return <code>String</code> ID of the Employee represented in object
     */
    public String getEmployeeID() {
        return employeeID;
    }
     /**
     * Returns the employee's phone number from this object
     * @return <code>String</code> phone number of the Employee represented in object
     */
    public String getPhoneNumber() {
        return phoneNumber;
    }
     /**
     * Returns the employee's street address from this object
     * @return <code>String</code> street address of the Employee represented in object
     */
    public String getStreetAddress(String streetAddress) {
        return streetAddress;
    }
     /**
     * Returns the employee's city from this object
     * @return <code>String</code> string of the Employee represented in object
     */
    public String getCity(String city) {
        return city;
    }
     /**
     * Returns the employee's state from this object
     * @return <code>String</code> state of the Employee represented in object
     */
    public String getState(String state) {
        return state;
    }
     /**
     * Returns the employee's zip code from this object
     * @return <code>String</code> zip code of the Employee represented in object
     */
    public String getZIP(String zip) {
        return zip;
    }
    /**
     * Returns the employee's date of birth from this object
     * @return <code>GregorianCalendar</code> date of birth of the Employee represented in object
     */
    public GregorianCalendar getDateOfBirth(GregorianCalendar dateOfBirth) {
        return dateOfBirth;
    }
    /**
     * Returns the employee's start date from this object
     * @return <code>GregorianCalendar</code> start date of the Employee represented in object
     */
    public GregorianCalendar getStartDate(GregorianCalendar startDate) {
        return startDate;
    }
    /**
     * Returns the employee's monthly salary from this object
     * @return <code>int</code> monthly salary of the Employee represented in object
     */
    public int getMonthlySalary(int monthlySalary) {
        return monthlySalary;
    }

    /**
     * calculateNetMonthly calculates the net pay for the employee by
     * subtracting the deductions for Federal Tax, State Tax, Retirement
     * savings, and health insurance from the gross pay
     */
    public double calculateNetMonthly(){
        deductionFederalTax = (monthlySalary * FEDERAL_TAX_PERCENT);
          deductionStateTax = (monthlySalary * STATE_TAX_PERCENT);
          deductionRetirement = (monthlySalary * RETIREMENT_SAVINGS_PERCENT);
          deductionHealth = (monthlySalary * HEALTH_INSURANCE_PERCENT);
          totalDeduction = (deductionFederalTax + deductionStateTax + deductionRetirement + deductionHealth);
          
        double netPay = (monthlySalary - totalDeduction);
        return netPay;
    }//end of calculateNetMonthly
    
     /**
     * This method) prints out all information about the employee
     */
    public void display(){
        System.out.println("Displaying Information for Employee:");
          System.out.println("Employee ID: " + employeeID);
          System.out.println("Employee name: " + employeeName);
          System.out.print("Birth date: "+ (dateOfBirth.get(Calendar.MONTH)+1)+
                "/"+dateOfBirth.get(Calendar.DATE)+"/"+ dateOfBirth.get(Calendar.YEAR)+"\n");
          System.out.print("Hire date: "+ (startDate.get(Calendar.MONTH)+1)+
                "/"+startDate.get(Calendar.DATE)+"/"+ startDate.get(Calendar.YEAR)+"\n");
          System.out.println("Employee phone number: " + phoneNumber);
          System.out.println("Employee street address: " + streetAddress);
          System.out.println("Employee city, state, and zip: " + city + ", " + state + " " + zip);
          System.out.println("The gross pay of the employee is: " + monthlySalary);
          
          
    }//end of display      
}//end of class FullTimeEmployee


CasualEmployee
CODE

/*
* CasualEmployee.java
*
* CSCE 155 Fall 2008
* Assignment 2
* @author Jared Wiebelhaus
* @version
*/

// import statements
import java.util.*;

public class CasualEmployee {

    //------------------Declare Constants---------------------------------------
    
    /**
     * Represents the percentage of the federal tax
     */
    private final double FEDERAL_TAX_PERCENT = 0.15;

    /**
     * Represents the percentage of the state tax
     */
    private final double STATE_TAX_PERCENT = 0.08;  
    
    //-------------Declare private variables-----------------------------------
    
    /**
     *variables used to hold the values for various information
      *about the employee including name, ID, phone number, street address,
      *city, state, and zip code
     */
    private String     employeeName;     
     private String    employeeID;
     private String phoneNumber;
     private String streetAddress;
     private String city;
     private String state;
     private String zip;
    
        private double weeklyPay;
     private double deductionFederalTax;
     private    double deductionStateTax;
    private double totalDeduction;
     private double netWeeklyPay;
     private int numberHours;
     private int totalHours;
     private double hourlyRate;
    
    /**
     * Represents the date of employment
     */
    private GregorianCalendar     startDate;
     /**
     * Represents the birth date for the employee
     */        
     private GregorianCalendar        dateOfBirth;
        
    /**
     * Constructor used to create this object.  Responsible for setting
     * all of this object's information to their corresponding default values
     */
    public CasualEmployee(){
        this.employeeName = "";
        this.employeeID = "";
          this.phoneNumber = "";
          this.streetAddress = "";
          this.city = "";
          this.state = "";
          this.zip = "";
    }//end of constructor
    
    /**
     * Returns the employee's name from this object
     * @return <code>String</code> Name of the Employee represented in object
     */
    public String getEmployeeName() {
        return employeeName;
    }
     /**
     * Returns the employee's ID from this object
     * @return <code>String</code> ID of the Employee represented in object
     */
    public String getEmployeeID() {
        return employeeID;
    }
     /**
     * Returns the employee's phone number from this object
     * @return <code>String</code> phone number of the Employee represented in object
     */
    public String getPhoneNumber() {
        return phoneNumber;
    }
     /**
     * Returns the employee's street address from this object
     * @return <code>String</code> street address of the Employee represented in object
     */
    public String getStreetAddress(String streetAddress) {
        return streetAddress;
    }
     /**
     * Returns the employee's city from this object
     * @return <code>String</code> string of the Employee represented in object
     */
    public String getCity(String city) {
        return city;
    }
     /**
     * Returns the employee's state from this object
     * @return <code>String</code> state of the Employee represented in object
     */
    public String getState(String state) {
        return state;
    }
     /**
     * Returns the employee's zip code from this object
     * @return <code>String</code> zip code of the Employee represented in object
     */
    public String getZIP(String zip) {
        return zip;
    }
    /**
     * Returns the employee's date of birth from this object
     * @return <code>GregorianCalendar</code> date of birth of the Employee represented in object
     */
    public GregorianCalendar getDateOfBirth(GregorianCalendar dateOfBirth) {
        return dateOfBirth;
    }
    /**
     * Returns the employee's start date from this object
     * @return <code>GregorianCalendar</code> start date of the Employee represented in object
     */
    public GregorianCalendar getStartDate(GregorianCalendar startDate) {
        return startDate;
    }

    /**
     * Sets the employee name represented by this object
     * @param employeeName the name of the employee
     */
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
    /**
     * Sets the employee ID represented by this object
     * @param employeeID the ID of the employee
     */
    public void setEmployeeID(String employeeID) {
        this.employeeID = employeeID;
    }
    /**
     * Sets the employee phone number represented by this object
     * @param phoneNumber the phone number of the employee
     */
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
    /**
     * Sets the employee street address represented by this object
     * @param streetAddress the street address of the employee
     */
    public void setStreetAddress(String streetAddress) {
        this.streetAddress = streetAddress;
    }
    /**
     * Sets the employee city represented by this object
     * @param city the city of the employee
     */
    public void setCity(String city) {
        this.city = city;
    }
    /**
     * Sets the employee state represented by this object
     * @param state the state of the employee
     */
    public void setState(String state) {
        this.state = state;
    }
    /**
     * Sets the employee zip code represented by this object
     * @param zip the zip code of the employee
     */
    public void setZIP(String zip) {
        this.zip = zip;
    }
    /**
     * Sets the employee date of birth represented by this object
     * @param dateOfBirth the birth date of the employee
     */
    public void setDateOfBirth(GregorianCalendar dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }
    /**
     * Sets the employee hiring date represented by this object
     * @param startDate the start date of the employee
     */
    public void setStartDate(GregorianCalendar startDate) {
        this.startDate = startDate;
    }
    
        /**
     * Returns the employee's total hours from this object
     * @return <code>int</code> total hours of the Employee represented in object
     */
    public int getTotalHours(int numberHours) {
        return numberHours;
    }

    /**
     * calculateNetWeekly calculates the net pay for the employee by
     * subtracting the deductions for Federal Tax and State Tax from
     * the weekly pay calculated from totalHours and hourlyRate
     */
        public void calculateNetWeekly(){
          totalHours = (numberHours * 5); // total hours for week = hours per day times 5 days for the week
          weeklyPay = (totalHours * hourlyRate); //total weekly pay = total hours times pay per hour
           deductionFederalTax = (weeklyPay * FEDERAL_TAX_PERCENT);
          deductionStateTax = (weeklyPay * STATE_TAX_PERCENT);
          totalDeduction = (deductionFederalTax + deductionStateTax);
          netWeeklyPay = (weeklyPay - totalDeduction);
        
    }//end of calculateNetWeekly
    
     /**
     * This method) prints out all information about the employee
     */
    public void display(){
        System.out.println("Displaying Information for Employee:");
          System.out.println("Employee ID: " + employeeID);
          System.out.println("Employee name: " + employeeName);
          System.out.print("Birth date: "+ (dateOfBirth.get(Calendar.MONTH)+1)+
                "/"+dateOfBirth.get(Calendar.DATE)+"/"+ dateOfBirth.get(Calendar.YEAR)+"\n");
          System.out.print("Hire date: "+ (startDate.get(Calendar.MONTH)+1)+
                "/"+startDate.get(Calendar.DATE)+"/"+ startDate.get(Calendar.YEAR)+"\n");
          System.out.println("Employee phone number: " + phoneNumber);
          System.out.println("Employee street address: " + streetAddress);
          System.out.println("Employee city, state, and zip: " + city + ", " + state + " " + zip);
          System.out.println("The gross pay of the employee is: " + weeklyPay);
          
          
    }//end of display      
}//end of class FullTimeEmployee


This post has been edited by Gerbilkit: 12 Oct, 2008 - 02:07 PM
User is offlineProfile CardPM

Go to the top of the page

Gerbilkit
post 13 Oct, 2008 - 07:30 PM
Post #4


New D.I.C Head

*
Joined: 1 Oct, 2008
Posts: 14

I'm getting a lot closer now but I'm a bit perplexed right now because I can't seem to find a class that allows me to do what I need. I am trying to read the file, and break it up into individual variables that can be used to construct objects in the ArrayList. I am trying to use a string tokenizer to do this, but I can't figure out how to access a particular token in the array. For instance I must access the first token so that I can determine what type of variables must be set on the object, and the tokens after that will determine the individual variables. As of now the only solution I can think of is first coding a loop, that assigns each token to a variable as they are found, I'm not quite sure how I would do this. Right now I can't even loop through the file because BufferedReader does not actually have a method hasNextLine(); more's the pity, so I will need some other way to make it loop through the whole file. Also I think that it could assign the tokens to a variable using the nextToken(); method. Something like
employeeType = nextToken();.

I used this tutorial quite a bit, however it is built to search for a particular string match, while I am trying to break up the line into tokens, save those to variables, so that they can be used to construct objects to be added to an arraylist. So I am not sure what parameter to pass to StringTokenizer since I am not searching for a string, and instead want to loop through each line and break it into tokens.

My thinking is a bit muddled, so I will make it more clear. My questions in order are:
  1. What method will allow me to make the BufferedReader loop through each line since hasNextLine() does not exist?
  2. What parameter should I pass to StringTokenizer to make it break each line up into tokens?
  3. What method should I use to assign each token to a variable, nextToken() is currently not recognized but I'm not sure I set it up correctly so that might still be a working method.

Thanks.

CODE

    public void generateArrayList() {
         try {
                // create a reader to read the file
                     FileReader freader = new FileReader(mainFile);
                BufferedReader bfreader = new BufferedReader(freader);
                                              
                // Loop through each line of the file and tokenize it.
                while (bfreader.hasNextLine()) { //method does not exist, what will loop through each line
                    StringTokenizer st = new StringTokenizer(parameter?);
                    
                    // loop through the tokens and create objects in the arraylist
                    while (st.hasMoreTokens()) {
                          //insert some code here to assign each new token to a specific variable
                          //such as
                          employeeType = nextToken(); // does not recognize nextToken()
                                                                  //as a valid method, wrong way to call it?
                          //employeeName = token;
                          //etc
                          }
                              }
                                    
                bfreader.close();
            }
            catch (IOException e) {
                // Print any error messages we happen to get related to opening and using the file.
                System.out.println(e.getMessage());
            }
        }// end generateArrayList

User is offlineProfile CardPM

Go to the top of the page

pbl
post 13 Oct, 2008 - 07:39 PM
Post #5


D.I.C Lover

Group Icon
Joined: 6 Mar, 2008
Posts: 2,982



Thanked 190 times

Dream Kudos: 75
My Contributions


String employeeType = st.nextToken();
User is offlineProfile CardPM

Go to the top of the page

Gerbilkit
post 14 Oct, 2008 - 03:57 AM
Post #6


New D.I.C Head

*
Joined: 1 Oct, 2008
Posts: 14

QUOTE(pbl @ 13 Oct, 2008 - 08:39 PM) *

String employeeType = st.nextToken();

Yeah I just realized that this morning, clearly I wasn't thinking clearly last night. Also since this is a string tokenizer all the temp variables will have to be strings, and I may have to typecast a few when I create the objects. I'll be able to get on again in a few hours and see if I figured this out.
User is offlineProfile CardPM

Go to the top of the page

Fast ReplyReply to this topicStart new topic
Time is now: 11/23/08 04:29AM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month