Results 1 to 3 of 3
  1. #1
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    60
    Rep Power
    0

    Default Using a FileRead as a database

    I remember, from a long time ago in class from my technical college days, that my teacher showed us that it's possible to collect multiple parameters from each line in a .txt file (with commas used as delimiters to separate each parameter on each line). My EmployeeData.txt file looks like this:

    EDR2014,Bob,Marley,02/12/2011,1000.00
    ARR1234,John,Fuzzy,03/23/2013,12.00
    XXX0666,Matt,Pagel,08/10/2011,23.00
    DIE4273,John,McLane,07/22/1995,45.00
    FUK0330,Kevin,Young,12/02/2003,7.00
    NFN7734,Sam,Peterson,08/01/1999,8.00

    the parameters of each line are:

    employeeNum, firstName, lastName, hireDate, payRate

    To match the specifications in the following EmployeeInfo.java class:

    Java Code:
    package employeepunch;
    //import org.joda.time.DateTime;
    import java.io.*;
    
    /**
     *
     * @author Sam Peterson
     */
    public class EmployeeInfo {
        
        public String firstName;
        public String lastName;
        public String employeeNum;
        public DateTime currentTime;
        public DateTime hireDate;
        public Double payRate;
        
        public String Seniority;
        public Double dailyTotal;
        
        public EmployeeInfo(String fName, String lName, String empNum,
                DateTime present, DateTime hired, Double pay, String senior,
                Double dayTotal)
        {
            firstName = fName;
            lastName = lName;
            employeeNum = empNum;
            currentTime = present;
            hireDate = hired;
            payRate = pay;
            
            //calculated parameters that will be outputted in EmployeePunch.java:
            Seniority = senior;
            dailyTotal = dayTotal;
        }
        //Read the info from EmployeeData.txt, and utilize it in this class, so that
        //it calculates the employee's seniority in years, months, days, hours,
        //and minutes. ALSO, we need this program to remember the exact date and
        //time that an employee punched in and out, so we can calculate exactly how
        //much money the employee earned that day.
        File myFile = new File("EmployeeData.txt");
        Scanner inputFile = new Scanner(myFile);
        
        //NOW WHAT?
        
        //When the employee's seniority and daily total are calculated, we pass
        //those 2 calculated parameters to EmployeePunch.java to be outputted out to
        //the employee as he punches out.    
        
    }//end of EmployeeInfo.java class
    And if you've read the comments, here is the "EmployeePunch.java" sub class:

    Java Code:
    /*
     * This class prompts the employee to punch in or out. If the employee
     * punches in, it simply says that he is punched in, and good bye. if 
     * he punches out, it tells that employee how much he made that day, how
     * long he's been with the company, and good bye.
     */
    package employeepunch;
    import java.util.Scanner;
    /**
     *
     * @author Sam Peterson
     */
    public class EmployeePunch {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            //1.)"Please Enter Employee Number."
            String employeeNum;  // To hold a customer number
          
          // Create a Scanner object for keyboard input.
          Scanner keyboard = new Scanner(System.in);
          
          System.out.println("Enter a customer number in "
                             + "the form LLLNNNN");
          System.out.print("(LLL = letters and NNNN "
                           + "= numbers): ");
    
          // Get a customer number from the user.
          customer = keyboard.nextLine();
          
          // DPPetermine whether it is valid.
          if (isValid(customer))
          {
             System.out.println("That's a valid customer "
                                + "number.");
          }
          else
          {
             System.out.println("That is not the proper "
                                + "format.");
             System.out.println("Here is an example: "
                                + "ABC1234");
          }
            
            //2.)"To Punch in, Press 1. To Punch out, press 2."
          /*
           * if 1 is pressed, simply say "Hello" + firstName + lastName ". You are"
           * + "punched in. Have a great day."
           * 
           * MAKE SURE A TIMER IS STARTED, SO THAT HIS WORK HOURS CAN BE USED TO
           * CALCULATE HIS PAY WHEN HE'S PUNCHING OUT!
           * 
           * if 2 is pressed, say "Thank you " + firstName + lastName ". You are"
           * + "punched out. You made " + dayTotal + "today. You've been with us "
           * + "for " + seniority_params_here + "Have a fantastic evening." 
           */
        }
    }//end of EmployeePunch.java class
    The validation of making sure the employee uses the correct format while entering his employee number is just the first part. I also need to add validation code to make sure his employee number matches one of the ones in the EmployeeData.txt file (shown earlier above).

    Can someone give me a boost on that? Thanks in advance.

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,785
    Blog Entries
    7
    Rep Power
    21

    Default Re: Using a FileRead as a database

    Have you read the API documentation for the String.split( ... ) method? It can do what you want: i.e. read entire lines and split( ... ) them.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    60
    Rep Power
    0

    Default Re: Using a FileRead as a database

    Keep in mind that I need more than just split strings. I need the separated pieces to become my parameters. The program must also be smart enough to get all those parameters for each employee on a per-line basis:

    Java Code:
    package employeepunch;
    //import org.joda.time.DateTime;
    import java.io.*;
    import java.util.StringTokenizer;
    import java.text.SimpleDateFormat;
    import java.util.Date;
     
    import org.joda.time.DateTime;
    import org.joda.time.Days;
    import org.joda.time.Hours;
    import org.joda.time.Minutes;
    import org.joda.time.Seconds;
    
    /**
     *
     * @author Sam Peterson
     */
    public class EmployeeInfo {
        
        public String firstName;
        public String lastName;
        public String employeeNum;
        public DateTime currentTime;
        public String hireDate;
        public Double payRate;
        
        public String Seniority;
        public Double dailyTotal;
        
        public EmployeeInfo(String fName, String lName, String empNum,
                DateTime present, String hired, Double pay, String senior,
                Double dayTotal)
        {
            firstName = fName;
            lastName = lName;
            employeeNum = empNum;
            currentTime = present;
            hireDate = hired;
            payRate = pay;
            
            //calculated parameters that will be printed out when employee punches
            //out in EmployeePunch.java:
            Seniority = senior;
            dailyTotal = dayTotal;
        }
        //Read the info from EmployeeData.txt, and use the tokens from each line 
        //(which are separated by commas as delimiters) as the values for each of
        //the variables/parameters specified above.
        public void fillParameters(){
            
            BufferedReader br = null;
     
    	try {
     
    		String line;
     
    		br = new BufferedReader(new FileReader("J:\\EmployeePunch\\EmployeePunch\\src\\employeepunch\\EmployeeData.txt"));
     
    		while ((line = br.readLine()) != null) {
    		   System.out.println(line);
     
    		   StringTokenizer stringTokenizer = new StringTokenizer(line, ",");
     
    		   while (stringTokenizer.hasMoreElements()) {
     
    		    //Integer id = Integer.parseInt(stringTokenizer.nextElement().toString());		    
                        //String employeeNum = stringTokenizer.nextElement().toString();
                        //String firstName = stringTokenizer.nextElement().toString();
                        //String lastName = stringTokenizer.nextElement().toString();
                        //String hireDate = stringTokenizer.nextElement().toString();
                        //Double payRate = Double.parseDouble(stringTokenizer.nextElement().toString());
     
    			StringBuilder sb = new StringBuilder();
    			sb.append("\nId : " + employeeNum);
                            sb.append("\nFirstName : " + firstName);
                            sb.append("\nLastName : " + lastName);
                            sb.append("\nSince : " + hireDate);
                            sb.append("\nWages : " + payRate);			
    			sb.append("\n*******************\n");
     
    			System.out.println(sb.toString());
    		   }
    		}//end of first try statement
    		System.out.println("Done");
     
    	} catch (IOException e) {
    		e.printStackTrace();
    	} finally {
    		try {
    			if (br != null)
    				br.close();
     
    		} catch (IOException ex) {
    			ex.printStackTrace();
    		}
    	}
            
        }//end of fillParameters() method
        
        public void calculateSeniority(){
            //String dateStart = hireDate;
            String dateStart = "01/14/2012 09:29:58";
    	String dateStop = "01/15/2012 10:31:48";
     
    	SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
     
    	Date d1 = null;
    	Date d2 = null;
     
    	try {
    		d1 = format.parse(dateStart);
    		d2 = format.parse(dateStop);
     
    		DateTime dt1 = new DateTime(d1);
    		DateTime dt2 = new DateTime(d2);
     
                    //ERROR: no suitable method found for daysBetween(DateTime,DateTime)
    		System.out.print(Days.daysBetween(dt1, dt2).getDays() + " days, ");
    		System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " hours, ");
    		System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " minutes, ");
    		System.out.print(Seconds.secondsBetween(dt1, dt2).getSeconds() % 60 + " seconds.");
     
    	 } catch (Exception e) {
    		e.printStackTrace();
    	 }
        }
        
        public void calculatePay(){
            dailyTotal = //(clockInTime - clockOutTime) * payRate;
            
        }
        
        
        //Set up string tokenizer to separately grab the parameters (as tokens) from
        //each line in EmployeeData.txt:
        
        //Make sure each one is viewed as a parameter, not just a mindless token 
        //string. For example the following line from EmployeeData.txt:
        
        //ARR1234,John,Fuzzy,03/23/2013,12.00
        
        //ARR1234 = employeeNum
        //John = firstName
        //Fuzzy = lastName
        //03/23/2013 = hireDate
        //12.00 = payRate
            
    }//end of EmployeeInfo.java class
    Also, in addition to being in the correct format, the entered employee number must also match with one of the employee numbers from the EmployeeData.txt file:

    Java Code:
    /**
        * The isValid method accepts the employee number the
        * user entered as a String as its argument, and makes
        * sure the number is in the correct format.
        */
    
       private static boolean isValid(String empNumber)
       {
          boolean goodSoFar = true;  // Flag
          int index = 0;             // Loop control variable
    
          // Is the string the correct length?
          if (empNumber.length() != 7)
             goodSoFar = false;
    
          // Test the first three characters for letters.
          while (goodSoFar && index < 3)
          {
             if (!Character.isLetter(empNumber.charAt(index)))
                goodSoFar = false;
             index++;
          }
    
          // Test the last four characters for digits.
          while (goodSoFar && index < 7)
          {
             if (!Character.isDigit(empNumber.charAt(index)))
                goodSoFar = false;
             index++;
          }
          
          /*
           * After confirming that the string entered by the user is in the correct
           * format, we now need to make sure it matches one of the employee numbers
           * in the EmployeeData.txt
           */
          
          while (goodSoFar != one of the empNumber in EmployeeData.txt)
          {
             if (!Character.match(empNumber.charAt(index)))
                goodSoFar = false;
             index++;
          }
    
          // Return the results
          return goodSoFar;
       }
    I think my format validation code looks okay, but I don't know how to fix the employee number matching validation.
    Last edited by SamJava_the_Hut; 03-08-2014 at 11:21 PM. Reason: I've added some code to start building the methods for calculating dailyTotal and seniority.

Similar Threads

  1. Create registration form | insert into database | call the database
    By FamilyGuy in forum JavaServer Pages (JSP) and JSTL
    Replies: 3
    Last Post: 04-23-2012, 12:08 PM
  2. Embedded Database : SQLite or Derby Database
    By vishnubrett in forum NetBeans
    Replies: 3
    Last Post: 03-26-2012, 11:50 AM
  3. Relational Database or Object Database?
    By mattlindsay in forum New To Java
    Replies: 8
    Last Post: 09-24-2011, 07:44 PM
  4. FileRead.java:79: cannot find symbol
    By xx__rose in forum New To Java
    Replies: 1
    Last Post: 05-09-2010, 05:06 AM
  5. Replies: 2
    Last Post: 02-11-2009, 05:43 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •