Solved

How many files and classes in JAVA

Posted on 2006-11-30
36
503 Views
Last Modified: 2013-11-23
hi,

I wanted to create a program in which i can read off a data file filled with employee data.

A major problem which i am facing is how many java files i have to create and how many classes and where to put what.

Ok this is what i want to create.

There are three types of employee Full time, Part time, and Commissioned each of them are assigned a work ID

the full time work 40 hrs per week whereas part time work depending on number of hours per week and are paid according to that.

the commissioned people have no number of hours but earn a basic wage of 1,200 and depending on number of sales either recieve 10% or if more than 100 then recieve 15%

Each employee is also assigned a level (i.e. according to which they are paid - whereas 1 is the lowest and 5 is the highest)


Now the program has to output data from the file showing in the right format.
and i also want to write back to the file in the correct format as shown below


FT, Jame Allison, 102384, 2, 2600 - this one is the salary they get.
PT, Hamed Jane, 103848, 10.5 - this one has the number of hours worked per week
CO, Jamie Jam, 283874, 4840 - this one has the salary including the commission

Any comments are welcomed

Thanx
0
Comment
Question by:junaid_raja30
  • 18
  • 15
36 Comments
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18049303
Well depending on how Object Oriented you want to go, you could have 4 classes for the model representation, namely:

abstract class Employee //common for all employees
class EmployeeFulltime extends Employee //specific for fulltime
class EmployeeParttime extends Employee //specific for parttime
class EmployeeCommissioned extends Employee //specific for commissioned

and another for reading/writing the employee data, just the program entry class (including the main method).

Of course, this can be an overkill if you just want a quick program todo the work. In such a case you can easily put everything in one class, but you lose a lot of flexibility.

If you go with the approach above, you can let the objects read and write themself to the file, which nicely separates the read/write syntax from the actually i/o calls. For example:

1. open file
2. emp = Employee.parse(file.readLine())
3. allEmps.add(emp)
4. iterate over allEmps
5. file.write(emp.toString());
6. close file

Sth like that. Good luck.
Mark


0
 

Author Comment

by:junaid_raja30
ID: 18061624
so i have another file known as sterling.java that actaully has details of how to output the money - i.e. the format

how can i use that in other files?
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18062351
Depends how the file is organized, I think methods in Sterling are static so you can just use:

String str = Sterling.myMoneyFormat(200);

or sth.. otherwise, you have to create an object(instance) of Sterling and do the same.

Mark
0
 

Author Comment

by:junaid_raja30
ID: 18062957
well this is the sterling code,


//  Sterling.java  

public class Sterling
{
   private int pound ;
   private int penny ;
   
 public Sterling()
   {
      pound = 0 ;
      penny = 0 ;
   }
   
      public Sterling( double d )
   {
      assert ( d >= 0.0 ) : "Sterling amount must be non-negative" ;
      pound = ( (int) (d * 100.0) ) / 100 ;
      penny = ( (int) (d * 100.0) ) % 100 ;
   }

     public Sterling( int pnds, int p )
   {
      assert (pnds >= 0) && (p >= 0) && (p <= 99) : "pounds & pence must be non-negative" ;
      pound  = pnds ;
      penny = p ;
   }

      public Sterling( Sterling s )
   {  
      pound  = s.pound ;
      penny = s.penny ;
   }

   public void setSterling( int pnds, int p )
   {
      assert (pnds >= 0) && (p >= 0) && (p <= 99) : "pounds & pence must be non-negative" ;
      pound = pnds ;
      penny = p ;
   }

     public Sterling add( Sterling s )
   {
      Sterling sum = new Sterling() ;
      int pennies = 100 * (pound + s.pound) + (penny + s.penny) ;
      sum.pound = pennies / 100 ;
      sum.penny = pennies % 100 ;
      return sum ;
   }  

     public Sterling subtract( Sterling s )
   {
      Sterling diff = new Sterling() ;
      int pennies = 100 * (pound - s.pound) + (penny - s.penny) ;
      diff.pound = pennies / 100 ;
      diff.penny = pennies % 100 ;
      return diff ;
   }

     public Sterling multiply( double m )
   {
      Sterling mult = new Sterling() ;
      double pennies = m * ( 100 * pound + penny ) ;
      mult.pound = (int) pennies / 100 ;
      mult.penny = (int) pennies % 100 ;
      return mult ;
   }

     public Sterling negative()
   {
      Sterling neg = new Sterling() ;
      int pennies = 100 * pound + penny ;
      neg.pound = -pennies / 100 ;
      neg.penny = -pennies % 100 ;
      return neg ;
   }  
   
 
   public boolean equals( Sterling s )
   {
      return ( (100*pound + penny) == (100*s.pound + s.penny) ) ;
   }

     public boolean lessThan( Sterling s )  
   {
      return ( (100*pound + penny) < (100*s.pound + s.penny) ) ;
   }

     public boolean greaterThan( Sterling s )  
   {
      return ( (100*pound + penny) > (100*s.pound + s.penny) ) ;
   }

     public void print()
   {
      String poundSign = "\u00a3" ;
 
      int temp = 100 * pound + penny ;
      if ( temp >= 0 )
      {
         if ( penny < 10 )
         {
            System.out.print( poundSign + pound + ":0" + penny ) ;
         }
         else
         {
            System.out.print( poundSign + pound +"." + penny ) ;
         }
      }
      else
      {
         if ( penny < 10 )
         {
            System.out.print( "-" + poundSign + -pound + ".0" + -penny ) ;
         }
         else
         {
            System.out.print( "-" + poundSign + -pound + "." + -penny ) ;
         }
      }
   }
}
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18062987
I would create a Sterling object in your Employee class (if they all use Sterling, otherwise in the subclass).
Make sure the subclasses make a call to the Employee superclass, otherwise the object won't be instantiated.

Mark
0
 

Author Comment

by:junaid_raja30
ID: 18063256
do you mean an object class such as the one below:

public abstract double sterling();

because every employee uses the sterling, but i am confused when u said make a call do you mean by using

super( sterling);


Thanx
Junaid
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18063306
abstract class Employee
{
    private Sterling sterling;
    public Employee() { this.sterling = new Sterling(); }
    public Employee(Sterling sterling) { this.sterling = sterling; }
}

class EmployeeFulltime extends Employee
{
    public EmployeeFulltime() { super(); }
    public EmployeeFulltime(double d) { super(new Sterling(d)); }
}

Of course it depends on how you are going to use all the classes, but i would expect sth like i stated above.

Another option is to make a static class which will handle all formatting, so you do not create a sterling object, but immediatly pass the parameters to a static format method, which will then calculate and format. Although this might not be possible since you seem to want to compare different Sterling objects.

Anyway, you should just try to solve the problem, and if it all works then you can always check your solution here with us. It is hard to give advice over a design, when you do not have full knowledge of the specifications. :-)

Mark
0
 

Author Comment

by:junaid_raja30
ID: 18063407
i mean i do have the specification but i am not giving all the details since i want to do it myself but while doing it i might require some help, which after trying to solve it i will post up....

But i need to learn as well so doint it ma self

But thanx alot for ur help bro
0
 

Author Comment

by:junaid_raja30
ID: 18063631
Just wanted to ask you one thing....

say if there were ranks between the PT and FT but not commissioned employees

do we set those ranks in the individual employee class or in the MAJOR employee class...?

e.g.

FT, rank1,
PT, rank2,  --> it can also be in rank1 depending on the type of person

so we use:
public void setGrade() -- in the PTEmployee and FTEmployee right?



Thanx
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18063662
Yes, that's a solution.

Another one which is even more OO would be to create an extra class RankedEmployee. So you get:

Employee = RankedEmployee            =PTEmployee
                                                      =FTEmployee
               = CommissionedEmployee

Obvious you would store the rank in RankedEmployee in this case.

Mark
0
 

Author Comment

by:junaid_raja30
ID: 18080464
Hey Mark,

Although i am still working on this file, but i have a problem here file shown below:

      public void setCommissionRate( double rate )
      {
            commissionRate = (( if sales <= 20000)
            {
                  rate = 10.0;
            }
            if (rate > 20000)
            {
                  rate = 15.0;
            })
      }
      
      public double getCommissionRate()
      {
            return commissionRate;
      }
      
      public void setTotalSales( double sales )
      {
            totalSales = (sales = 20000);
            //totalSales = (sales < 0.0 ) ? 0.0 : sales
            //Sales must not be negative
      }
      
      public double getTotalSales()
      {
            return totalSales;
      }


Basically i have to put that if the totalSales of the employee is less than 20,000 then the commission rate is more than 10 %, but if more than 20,000 then 15 %

But i am confused that the totalSales must not be a negative number so i am not sure what to put in the setTotalSales function?

Please could you help

Thanx
Junaid
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18080511
You mean this?

public void setCommissionRate( double rate )
     {
          commissionRate = (sales < 20000) ? 10.0 : 15.0;
     }
     
     public double getCommissionRate()
     {
          return commissionRate;
     }
     
     public void setTotalSales( double sales )
     {
          totalSales = (sales < 0.0 ) ? 0.0 : sales;
     }
     
     public double getTotalSales()
     {
          return totalSales;
     }

Mark
0
 

Author Comment

by:junaid_raja30
ID: 18080568
so Mark do you mind explaining to me

what does the "?" mean in this case and then the ":"

Thanks
Junaid
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18080577
short notation for:

condition ? then-part : else-part

if(condition)
{
then-part
}
else
{
else-part
}

Mark
0
 

Author Comment

by:junaid_raja30
ID: 18098156
Thanx Mark for the previous explanation, i just wanted to ask is it possible to put the following in a short notation:

public void setMonthlySalary( salary )
      {
            MonthlySalary = salary;
      }
            
      public double getMonthlySalary()
      {
            if (grade == 1)
            {
                  salary = 1600;
            }
            else if (grade == 2)
            {
                  salary = 1750;
            }
            else if (grade == 3)
            {
                  salary = 1900;
            }
            else if (grade == 4)
            {
                  salary = 2100;
            }
            else if (grade == 5)
            {
                  salary = 2300;
            }
            
            return salary;
      }


Also i think the if...else if statement should be in the setter method? What do you say?

Thanx
Junaid
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18100026
if you have a setGrade() then i guess you should put it there.
Shorter version uses switch statement:

switch grade
{
  case 1:
    salary = 1600;
    break;
  case 2:
    salary = 1750;
    break;
  case 3:
    salary = 1900;
    break;
  case 4:
    salary = 2100;
    break;
  case 5:
    salary = 2300;
    break;
  default:
    salary = 0;
    break;
}

Or.. you could also do sth like:

int[] sallaries = new int[]{1600, 1750, 1900, 2100, 2300};
salary = (grade>0 && grade<6) ? sallaries[grade-1] : 0;

Mark
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:junaid_raja30
ID: 18107570
thanx for that mark, now i am supposed to create a vector class which will store and sort the employees by name?
I understand what a vector is but fail to understand how to implement a vector?

Could you provide some detail?

Thanx
Junaid
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18107651
There is a default implementation for vectors.
Take a look here:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Vector.html
http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html
http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html

Lots of standard implementation, all slighltly different
In the end it will look like:

LinkedList emps = new LinkedList();

while(...)
   emps.add(emp.getName());

Collections.sort(emps);

Mark
0
 

Author Comment

by:junaid_raja30
ID: 18108136
Hey thanx Mark,

i am still working on the vector although in the mean time do you mind checking the other JAVA files.

below is Employee.java

//File: Employee.java
//This class defines the superclass of the employee details.
            
            package Sterling
            
public abstract class Employee
{
      private String typeOfEmployee;
      private String fullName;
      private int workNumber;
      private Sterling sterling

      public Employee( String typeOfEmployee, String fullName, int workNumber )
      {
            typeOfEmployee = type;
            fullName = name;
            workNumber = id;
            this.sterling = new Sterling();
      }

      public Employee(Sterling sterling)
      {
            this.sterling = sterling;
      }

      public void setTypeOfEmployee( String type )
      {
      typeOfEmployee = type;
      }

      public String getTypeOfEmployee()
      {
            return typeOfEmployee;
      }
      
      public void setFullName( String name )
      {
            fullName = name;
      }
      
      public String getFullname()
      {
            return fullName;
      }
      
      public void setWorkNumber( int id )
      {
            workNumber = id; //Should be validated
      }
      
      public int getWorkNumber()
      {
            return workNumber;
      }
      
      public String toString()
      {
            return String.format( "%s, %s, %s, ", getTypeOfEmployee(), getFullname(), getWorkNumber() );
      }
      
      public abstract double pay();
}



Below is the FTEmployee.java


//File:      FTEmployee.java
//This file      is an      extension      to Employee.java for Full      Time Employee

package Employee;

public class FTEmployee      extends      Employees
{
      private      double ftSalary;
      
      public FTEmployee( String type, String name, int id, double salary, int grade )
      {
            super( type, name, id );
            setGrade( grade );
            setMonthlySalary( salary );
      }

      public FTEmployee( double d )
      {
            super( new sterling( d ));
      }
      
      public void setGrade( grade )
      {
            Grade = grade;
            
            int[] gradedFTsalary = new int[]{1600, 1750, 1900, 2100, 2300};
            salary = (grade>0 && grade<6) ? gradedFTsalary[grade-1] : 0;      
      }
      
      public int getGrade()
      {
            return grade;
      }
      
      public void setMonthlySalary( salary )
      {
            MonthlySalary = salary;
      }
            
      public double getMonthlySalary()
      {
            return salary;
      }
      
      public double pay()
      {
            return getMonthlySalary();
      }
      
      public String toString()
      {
            return String.format("%s,%s,%d,%d,%s=> £%,.2f", super.toString(), getGrade(), "Monthly Salary", getMonthlySalary());
      }
}



Below is the PTEmployee.java

//File: PTEmployee.java
//A class designed for the Part-Time Employees

package Employee;

public class PTEmployee extends Employee
{
      private double wage;
      private double hours;
      
      public PTEmployee( String type, String name, int id, double salary, int grade, double hourlyWage, double hoursWorked)
      {
            super( type, name, id )
            setGrade( grade );
            setPTSalary( salary );
            setWage( hourlyWage );
            setHours( hoursWorked );
      }
      
      public PTEmployee( double d )
      {
            super( new sterling( d ));
      }
      
      public void setGrade( grade )
      {
            Grade = grade;
      
            int[] gradedPTsalary = new int[]{1600, 1750, 1900, 2100, 2300};
            salary = (grade>0 && grade<6) ? gradedPTsalary[grade-1] : 0;      
            
      }
      
      public int getGrade()
      {
            return grade;
      }
            
      public setHours( double hoursWorked )
      {
            hours = ( ( hoursWorked >= 0.0 ) && ( hoursWorked <= 40.0)) ? hoursWorked : 0.0;
      }
      
      public double getHours()
      {
            return hours;
      }
      
      public void setPTSalary ( salary )
      {
            PTSalary = salary;
      }

      public double getPTSalary()
      {
            return salary;
      }
      
      public double pay()
      {
            if (getHours() <= 40.0)
            getPTSalary * getHours()/40;
      }
      
      public String toString()
      {
            return String.format( "%s,%s,%d,%,.2f,%s=>,£%,.2f", super.toString(), getGrade(), getHours(), "Monthly Salary", PTEmployee.pay())
      }
}



Below is the COEmployee.jaav


//File: COEmployee.java
//This file is an extension to the Employee class which contains the Commission Employees

public class COEmployee extends Employee
{
      private double basicSalary;
      private double commissionRate;
      private double totalSales;
      
      public COEmployee( String type, String name, int id, double salary, double rate, double sales )
      {
            super( type, name, id );
            setBasicSalary( salary );
            setCommissionRate( rate );
            setTotalSales( sales );
      }
      
      public void setCommissionRate( double rate )
  {
         commissionRate = (sales < 20000) ? 10.0 : 15.0;
  }
     
  public double getCommissionRate()
  {
     return commissionRate;
  }
     
  public void setTotalSales( double sales )
  {
         totalSales = (sales < 0.0 ) ? 0.0 : sales;
  }
     
  public double getTotalSales()
  {
         return totalSales;
  }

      public void setBasicSalary( double salary )
      {
             basicSalary = ( salary < 1200 ) ? 0.0 : salary
      }
      
      public double getBasicSalary()
      {
            return basicSalary;
      }
      
      //Call an overriden method from the Employee.java - remember to create a calcpay() method
      
      public double pay()
      {
            basicSalary + ((commissionRate/100)*totalSales);
      }
      
}            


Please let me know if there is anything wrong, however it did compile from my side.

Thanks

Junaid
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18108200
Where is the Sterling class?

How are you going to use these classes? What is the bigger picture here?

There are various errors in your files, typo's and wrong uses. Maybe it makes more sense to have an idea of what you want to build and then i can comment on the way you approached the problem.

So, please supply a concrete use of these classes, or at least some specifications.

Mark
0
 

Author Comment

by:junaid_raja30
ID: 18109309
This work centres on building your own class hierarchy Employee together with the use of a library class, Sterling, which I have written which you will use to represent currency values. You will also explore Java's String, StringTokenizer and Vector classes which you will use to parse input data, (supplied as a data file) into individual strings. The interface for the Sterling class can be found here, while the corresponding implementation of the class, Sterling.java can be copied across from here.


A large car dealing company wants to write a computer system to store information about its staff and to perform routine payroll tasks. For each member of staff, the following information needs to be provided: the name, an employee works number (this is a unique 6-digit number) together with an operation to calculate the employee's monthly salary.

The company employs both full-time and part-time staff where the part-time staff work for a specified number of hours per week. Full-time staff are assumed to work for 40 hours per week and part-time staff are paid pro rata, so for example if a part-time employee works for 15 hours per week, s/he will recieve three eights (15/40) of the monthly salary of a full-time employee on the same grade. These staff are paid on a 5-point salary scale (which include all on-costs such as income tax, national insurance and pension contributions) and is shown below.

 


Spine Point          Monthly Salary
 
1                           £1,600
 
2                           £1,750
 
3                           £1,900
 
4                          £2,100
 
5                          £2,300
 


 

The company also employs commissioned people (car salesmen and saleswomen) whose monthly salary is made up of a basic flat rate minimum of £1,200 plus a percentage their total sales for that month. The rate of commission for sales up to but not exceeding £20,000 is 10% while for sales exceeding £20,000, the commission rate is 15%.

 

Define a hierarchy of Java classes that meets the above requirements


Define a class StaffList to represent a directory (i.e. list) of employees that can be used to store the details of all the company's employees. Your staff list class needs to include a container object as one of its instance variables - this could be an array, a Vector, or a Collections object. Think carefully about the type of objects the directory should store and the interface it provides


Write a short main program that does the following:


reads a list of employee details from the comma delimited data file "staff06.dat" (which can be copied across from here) and places them into the directory
calculates the salaries of all staff in the company
prints out, in tabular form, the details and salaries of all staff in the company, with names in alphabetical order
prints out the total monthly salary bill
Your main program should include a method void doPayroll ( ... ) that takes a list of staff, calculates their monthly salary and writes their details and individual salaries, appropriately formatted, to the standard output.

The data file includes the following codes:


Code       Type of Employee
 
FT           Full-time Salaried
 
PT           Part-time Salaried
 
CO          Commissioned (Salesperson)
 


Typical data entries for a full-time, part-time and a commissioned employee respectivley, take the forms below, where each field is separated by a comma with no white space:

FT,name,works-number,grade
PT,name,works-number,grade,hours-worked
CO,name,works-number,monthly-sales-total

with typical entries shown below

      FT,DICKENS Charles,234567,4
      PT,AUSTEN Jane,111222,5,10.5
      CO,HARDY Thomas,777333,6500



I have given the sterling.java above in a previous post. But again i have given it below:



//  Sterling.java  

public class Sterling
{
   private int pound ;
   private int penny ;
   
 public Sterling()
   {
      pound = 0 ;
      penny = 0 ;
   }
   
      public Sterling( double d )
   {
      assert ( d >= 0.0 ) : "Sterling amount must be non-negative" ;
      pound = ( (int) (d * 100.0) ) / 100 ;
      penny = ( (int) (d * 100.0) ) % 100 ;
   }

     public Sterling( int pnds, int p )
   {
      assert (pnds >= 0) && (p >= 0) && (p <= 99) : "pounds & pence must be non-negative" ;
      pound  = pnds ;
      penny = p ;
   }

      public Sterling( Sterling s )
   {  
      pound  = s.pound ;
      penny = s.penny ;
   }

   public void setSterling( int pnds, int p )
   {
      assert (pnds >= 0) && (p >= 0) && (p <= 99) : "pounds & pence must be non-negative" ;
      pound = pnds ;
      penny = p ;
   }

     public Sterling add( Sterling s )
   {
      Sterling sum = new Sterling() ;
      int pennies = 100 * (pound + s.pound) + (penny + s.penny) ;
      sum.pound = pennies / 100 ;
      sum.penny = pennies % 100 ;
      return sum ;
   }  

     public Sterling subtract( Sterling s )
   {
      Sterling diff = new Sterling() ;
      int pennies = 100 * (pound - s.pound) + (penny - s.penny) ;
      diff.pound = pennies / 100 ;
      diff.penny = pennies % 100 ;
      return diff ;
   }

     public Sterling multiply( double m )
   {
      Sterling mult = new Sterling() ;
      double pennies = m * ( 100 * pound + penny ) ;
      mult.pound = (int) pennies / 100 ;
      mult.penny = (int) pennies % 100 ;
      return mult ;
   }

     public Sterling negative()
   {
      Sterling neg = new Sterling() ;
      int pennies = 100 * pound + penny ;
      neg.pound = -pennies / 100 ;
      neg.penny = -pennies % 100 ;
      return neg ;
   }  
   
 
   public boolean equals( Sterling s )
   {
      return ( (100*pound + penny) == (100*s.pound + s.penny) ) ;
   }

     public boolean lessThan( Sterling s )  
   {
      return ( (100*pound + penny) < (100*s.pound + s.penny) ) ;
   }

     public boolean greaterThan( Sterling s )  
   {
      return ( (100*pound + penny) > (100*s.pound + s.penny) ) ;
   }

     public void print()
   {
      String poundSign = "\u00a3" ;
 
      int temp = 100 * pound + penny ;
      if ( temp >= 0 )
      {
         if ( penny < 10 )
         {
            System.out.print( poundSign + pound + ":0" + penny ) ;
         }
         else
         {
            System.out.print( poundSign + pound +"." + penny ) ;
         }
      }
      else
      {
         if ( penny < 10 )
         {
            System.out.print( "-" + poundSign + -pound + ".0" + -penny ) ;
         }
         else
         {
            System.out.print( "-" + poundSign + -pound + "." + -penny ) ;
         }
      }
   }
}


0
 

Author Comment

by:junaid_raja30
ID: 18110486
Ok i have posted the specification, may i know what the problems are?
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18110493
Alright, it is easier than you are doing now. With these kind of assignments you just have to read very carefully and do exactly what they ask. I will show you how:

The employee class works as follow, you take the specification and look for fieldnames. Read and discover..

/**
 * Employee
 *
 * A large car dealing company wants to write a computer system to store
 * information about its staff and to perform routine payroll tasks. For
 * each member of staff, the following information needs to be provided:
 * the name, an employee works number (this is a unique 6-digit number)
 * together with an operation to calculate the employee's monthly salary.
 */
public abstract class Employee
{
    private String name ;
    private int workNumber ;

    public Employee( String name, int workNumber )
    {
        this.name = name ;
        this.workNumber = workNumber ;
    }

    public abstract double calcMonthlySalary() ;
}

Nothing more, nothing less (for now at least). Then you move to the next piece of your specification.

This is a bit more complicated, you have to make a difference beween full-time and part-time. First you try the full-time employee, which is clearly stated below.

/**
 * FullTimeEmployee
 *
 * The company employs both full-time and part-time staff where the
 * part-time staff work for a specified number of hours per week.
 * Full-time staff are assumed to work for 40 hours per week and
 * ...
 * These staff are paid on a 5-point salary scale (which include
 * all on-costs such as income tax, national insurance and pension
 * contributions) and is shown below.
 *
 * +-------------+----------------+
 * | Spine Point | Monthly Salary |
 * +-------------+----------------+
 * |      1      |     £1,600     |
 * |      2      |     £1,750     |
 * |      3      |     £1,900     |
 * |      4      |     £2,100     |
 * |      5      |     £2,300     |
 * +-------------+----------------+
 */
public class FullTimeEmployee extends Employee
{
    private final static Sterling[] salaryScale = { new Sterling( 1600.0 )
                                                  , new Sterling( 1750.0 )
                                                  , new Sterling( 1900.0 )
                                                  , new Sterling( 2100.0 )
                                                  , new Sterling( 2300.0 ) } ;

    private int grade ;

    public FullTimeEmployee( String name, int workNumber, int grade )
    {
        super(name, workNumber) ;

        assert (grade >= 1) && (grade <= 5) : "grade must be beween 1 and 5" ;
        this.grade = grade ;
    }

    public Sterling calcMonthlySalary()
    {
        return FullTimeEmployee.salaryScale[this.grade-1] ;
    }
}

For part-time you do a similar thing, only now there are different implementations possible. Below is the one where you let the PartTimeEmployee extend the FullTimeEmployee. Since you can call the calcMonthlySalary from your superclass, you can get the payement if you were a full-time employee, of course you are not, so you should multiply by a factor (depending on your hours).

/**
 * PartTimeEmployee
 *
 * ...
 * part-time staff are paid pro rata, so for example if a part-time
 * employee works for 15 hours per week, s/he will recieve three eights
 * (15/40) of the monthly salary of a full-time employee on the same
 * grade.
 * ...
 */
public class PartTimeEmployee extends FullEmployee
{
    private double hoursWorked ;

    public PartTimeEmployee( String name, int id, int grade, double hoursWorked)
    {
        super( name, id, grade ) ;

        assert (hoursWorked >= 0.0) && (hoursWorked <= 40.0) : "at least 0 hours work and maximum of 40" ;
        this.hoursWorked = hoursWorked ;
    }

    public Sterling calcMonthlySalary()
    {
        Sterling fulltime = super.calcMonthlySalary() ;
        return fulltime.multiply( hoursWorked / 40.0 ) ;
    }
}

Notice how the values are passed to the constructors and how they look similar to the Sterling class. It's always a good idea to adopt your coding style to the previous done work, that makes changes transparent and easy to read. There is no need for set-ters/get-ters at this moment, maybe we need them later. Also note that you HAVE to use the Sterling class to express valuta, otherwise it would be useless, and that's stupid to assume, since they want you to use it!!

Now the CommissionedEmployee is different, but I guess you can figure this out yourself. I have the class available, but you first try yourself. Let me know how you implemented this class with my advice.

So if you have come to this point then you are at this point: "Define a hierarchy of Java classes that meets the above requirements" in the specification. Now, I will not give you straight implementations of the rest of the specifications, but let me try to point you in the right direction.

1. Define another class StaffList, which contains a list of employees. This is sort of a wrapper class around a Collection class. You can use any type of collection, I would suggest a LinkedList since it's easy and well-known, a vector is also possible. If you use Java 5.0 you can use generics (probably unfamilar with that) to remove some castings, but you can also write the same in 1.4.

2. Write a parser for the staff data-file. Just read every line in the data file and split the string on ",". Next you parse the type and select the correct branch to continue parsing. Something like:
if( "FT".equals(stype) )
{
    new FullTimeEmployee( ... ) ;
}
else if( "PT".equals(stype) )
{
    new PartTimeEmployee( ... ) ;
}
else if( "CO".equals(stype) )
{
    new CommissionedEmployee( ... ) ;
}
else
{
    //Unknown type.
}

That should help you with the parsing piece. Do not forget to catch all the number format exceptions and other possibly wrong input data, it shows good programming skills.
3. Next you have to perform some I/O to show that your class hierarchy works. Basically this is a lot of pretty printing of salaries, but since the Sterling class already has a print (which you should use), you can make this fairly easy. Sorting can be done very effective by the Collections (notice the 's') class, look it up on google and you will see sth like: Collections.sort( ... ) ;

Well obvious there is still some work to be done. I have always liked these kind of assignments, since they can be done in a very clean and OO way, but it is not my job to do your homework (even if I would love to). So I hope you can build on the base i provided and always try to find a nice clean and small solution. It always looks way easier if you see the solution in front of you..

Good luck,
Mark
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18110569
I completed the exercise and I noticed some typos/compile errors. I hope you won't be bother too much, they are not difficult to solve. Mostly I forgot to add/change things.

You might want to leave out the number format exception checks, but you may want to ask the teacher about that.

Also, with generics, the whole idea of a StaffList is rather dumb, but it's do-able. I can give you my source anytime you want, but I don't think you are allowed to use other peoples solutions.

Anyway, good luck
Mark
0
 

Author Comment

by:junaid_raja30
ID: 18110598
Hey Thanx alot Mark, Below is my commissioned Employee file:

Will add the comments later.

public class CommissionEmployee extends Employee
{
      private double basicSalary;
      private double commissionRate;
      private double totalSales;
      
      public COEmployee( String type, String name, int id, double salary, double rate, double sales )
      {
            super( type, name, id );
            
            assert ( salary < 1200 ) ? 0.0 : salary; //Basic Salary is £1,200
            this.salary = salary;
            
            assert (sales < 20000) ? 10.0 : 15.0; //if more than £20,000 then 15%, if less than £20,000 its 10%
            this.rate = rate;
            
            assert (sales < 0.0 ) ? 0.0 : sales; //So that no sales are negative numbers
            this.sales = sales
      }
      
      public Sterling calcMonthlySalary()
      {
            basicSalary + ((commissionRate/100)*totalSales);
      }
      
0
 

Author Comment

by:junaid_raja30
ID: 18110601
Oops sorry i just noted a mistake, the private member are named wrong... it should be salary, sales, and rate...
0
 

Author Comment

by:junaid_raja30
ID: 18110671
ok the other thing i wanted to ask we have to use :

Package Sterling

in Employee.java
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18110691
ehh? sterling is not a package, sterling is a class and my version of Employee uses Sterling as return type of calcMontlhySalary.

Compare your class CommissionedEmployee with this one:

/**
 * CommissionedEmployee
 *
 * The company also employs commissioned people (car salesmen and saleswomen)
 * whose monthly salary is made up of a basic flat rate minimum of £1,200
 * plus a percentage their total sales for that month. The rate of commission
 * for sales up to but not exceeding £20,000 is 10% while for sales exceeding
 * £20,000, the commission rate is 15%.
 */
public class CommissionedEmployee extends Employee
{
    private final static Sterling basicFlatRate = new Sterling(1200.0) ;

    private Sterling monthlySalesTotal;

    public CommissionedEmployee( String name, int id, Sterling monthlySalesTotal )
    {
        super( name, id ) ;

        this.monthlySalesTotal = monthlySalesTotal ;
    }

    public Sterling calcMonthlySalary()
    {
        double commissionRate = monthlySalesTotal.lessThan( new Sterling( 20000 ) ) ? 10.0 : 15.0 ;
        Sterling commission = monthlySalesTotal.multiply( commissionRate / 100.0 ) ;
        return basicFlatRate.add( commission ) ;
    }
}

Mark
0
 

Author Comment

by:junaid_raja30
ID: 18110724
The reason why i said about the package is because while compiling the Sterling.java with Employee.java and FullTimeEmployee.java,

I recieved errors about that the abstract written below:

FullTimeEmployee.java:1: FullTimeEmployee is not abstract and does not override abstract method calcMonthlySalary() in Employee
public class FullTimeEmployee extends Employee
       ^
FullTimeEmployee.java:19: calcMonthlySalary() in FullTimeEmployee cannot override calcMonthlySalary() in Employee; attempting to use incompatible return type
found   : Sterling
required: double
    public Sterling calcMonthlySalary()


But what i thought also is to use package Employee in FullTime Employee?

0
 

Author Comment

by:junaid_raja30
ID: 18110788
i guess i need an interface class right?
0
 
LVL 10

Accepted Solution

by:
ADSLMark earned 140 total points
ID: 18110802
I told you, there were some mistakes in my initial post.. anyway.. this is already a pretty long thread..
Here is my version of the whole assignment. I am not saying that it's completely correct, since I made it in like.. 1 hour (?) so you might still have todo some checks and tests.

/**
 * Employee
 *
 * A large car dealing company wants to write a computer system to store
 * information about its staff and to perform routine payroll tasks. For
 * each member of staff, the following information needs to be provided:
 * the name, an employee works number (this is a unique 6-digit number)
 * together with an operation to calculate the employee's monthly salary.
 */
public abstract class Employee implements Comparable<Employee>
{
    private String name ;
    private int workNumber ;

    public Employee( String name, int workNumber )
    {
        this.name = name ;
        this.workNumber = workNumber ;
    }

    public int compareTo( Employee employee )
    {
        return this.name.compareTo( employee.name ) ;
    }

    public void print()
    {
        System.out.print(this.name + "\t" + this.workNumber);
    }

    public abstract Sterling calcMonthlySalary() ;
}

/**
 * CommissionedEmployee
 *
 * The company also employs commissioned people (car salesmen and saleswomen)
 * whose monthly salary is made up of a basic flat rate minimum of £1,200
 * plus a percentage their total sales for that month. The rate of commission
 * for sales up to but not exceeding £20,000 is 10% while for sales exceeding
 * £20,000, the commission rate is 15%.
 */
public class CommissionedEmployee extends Employee
{
    private final static Sterling basicFlatRate = new Sterling(1200.0) ;

    private Sterling monthlySalesTotal;

    public CommissionedEmployee( String name, int id, Sterling monthlySalesTotal )
    {
        super( name, id ) ;

        this.monthlySalesTotal = monthlySalesTotal ;
    }

    public Sterling calcMonthlySalary()
    {
        double commissionRate = monthlySalesTotal.lessThan( new Sterling( 20000 ) ) ? 10.0 : 15.0 ;
        Sterling commission = monthlySalesTotal.multiply( commissionRate / 100.0 ) ;
        return basicFlatRate.add( commission ) ;
    }
}

/**
 * FullTimeEmployee
 *
 * The company employs both full-time and part-time staff where the
 * part-time staff work for a specified number of hours per week.
 * Full-time staff are assumed to work for 40 hours per week and
 * ...
 * These staff are paid on a 5-point salary scale (which include
 * all on-costs such as income tax, national insurance and pension
 * contributions) and is shown below.
 *
 * +-------------+----------------+
 * | Spine Point | Monthly Salary |
 * +-------------+----------------+
 * |      1      |     £1,600     |
 * |      2      |     £1,750     |
 * |      3      |     £1,900     |
 * |      4      |     £2,100     |
 * |      5      |     £2,300     |
 * +-------------+----------------+
 */
public class FullTimeEmployee extends Employee
{
    private final static Sterling[] salaryScale = { new Sterling( 1600.0 )
                                                  , new Sterling( 1750.0 )
                                                  , new Sterling( 1900.0 )
                                                  , new Sterling( 2100.0 )
                                                  , new Sterling( 2300.0 ) } ;

    private int grade ;

    public FullTimeEmployee( String name, int workNumber, int grade )
    {
        super(name, workNumber) ;

        assert (grade >= 1) && (grade <= 5) : "grade must be beween 1 and 5" ;
        this.grade = grade ;
    }

    public Sterling calcMonthlySalary()
    {
        return FullTimeEmployee.salaryScale[this.grade-1] ;
    }
}

/**
 * PartTimeEmployee
 *
 * ...
 * part-time staff are paid pro rata, so for example if a part-time
 * employee works for 15 hours per week, s/he will recieve three eights
 * (15/40) of the monthly salary of a full-time employee on the same
 * grade.
 * ...
 */
public class PartTimeEmployee extends FullTimeEmployee
{
    private double hoursWorked ;

    public PartTimeEmployee( String name, int id, int grade, double hoursWorked)
    {
        super( name, id, grade ) ;

        assert (hoursWorked >= 0.0) && (hoursWorked <= 40.0) : "at least 0 hours work and maximum of 40" ;
        this.hoursWorked = hoursWorked ;
    }

    public Sterling calcMonthlySalary()
    {
        Sterling fulltime = super.calcMonthlySalary() ;
        return fulltime.multiply( hoursWorked / 40.0 ) ;
    }
}

/**
 * StaffList
 *
 * Define a class StaffList to represent a directory (i.e. list) of employees
 * that can be used to store the details of all the company's employees. Your
 * staff list class needs to include a container object as one of its instance
 * variables - this could be an array, a Vector, or a Collections object.
 * Think carefully about the type of objects the directory should store and
 * the interface it provides.
 */

import java.util.*;

public class StaffList
{
    private LinkedList<Employee> list ;

    public StaffList()
    {
        this.list = new LinkedList<Employee>();
    }

    public void addEmployee( Employee employee )
    {
        this.list.add( employee ) ;
    }

    public void sortStaffList()
    {
        Collections.sort(this.list) ;
    }

    public Sterling sumSalaries()
    {
        Sterling sum = new Sterling( 0.0 ) ;

        for(Employee employee : list)
        {
            Sterling salary = employee.calcMonthlySalary() ;
            sum = sum.add(salary) ;
        }

        return sum ;
    }

    public void print()
    {
        System.out.println("Name\t\tWork number\tSalary") ;
        for(Employee employee : list)
        {
            Sterling salary = employee.calcMonthlySalary() ;

            employee.print() ;
            System.out.print("\t\t") ;
            salary.print() ;
            System.out.println() ;
        }
    }
}

/**
 * StaffMain
 *
 * Write a short main program that does the following:
 *
 * - reads a list of employee details from the comma delimited
 *   data file "staff06.dat" (which can be copied across from
 *   here) and places them into the directory
 * - calculates the salaries of all staff in the company
 * - prints out, in tabular form, the details and salaries
 *   of all staff in the company, with names in alphabetical order
 * - prints out the total monthly salary bill
 *
 * Your main program should include a method void doPayroll ( ... )
 * that takes a list of staff, calculates their monthly salary and
 * writes their details and individual salaries, appropriately
 * formatted, to the standard output.
 *
 * The data file includes the following codes:
 *
 * +------+-----------------------------+
 * | Code | Type of Employee            |
 * +------+-----------------------------+
 * | FT   | Full-time Salaried          |
 * | PT   | Part-time Salaried          |
 * | CO   | Commissioned (Salesperson)  |
 * +------+-----------------------------+
 *
 * Typical data entries for a full-time, part-time and a commissioned
 * employee respectivley, take the forms below, where each field is
 * separated by a comma with no white space:
 *
 * FT,name,works-number,grade
 * PT,name,works-number,grade,hours-worked
 * CO,name,works-number,monthly-sales-total
 *
 * with typical entries shown below:
 *
 *       FT,DICKENS Charles,234567,4
 *       PT,AUSTEN Jane,111222,5,10.5
 *       CO,HARDY Thomas,777333,6500
 */

import java.io.*;

public class StaffMain
{
    public static StaffList readFile(String filename)
    {
        StaffList list = new StaffList() ;

        try
        {
            String line = null ;
            int lineNr = 0 ;
            BufferedReader br = new BufferedReader( new FileReader( filename ) ) ;
            while((line = br.readLine()) != null)
            {
                String[] fields = line.split(",");
                if( fields.length == 0 )
                {
                    System.out.println("["+filename+": "+lineNr+"] Expecting type field (PT/FT/CO).") ;
                    continue ;
                }

                if( "FT".equals(fields[0]) )
                {
                    String name = fields[1] ;
                    int workNumber = Integer.parseInt(fields[2]) ;
                    int grade = Integer.parseInt(fields[3]) ;
                    list.addEmployee( new FullTimeEmployee( name, workNumber, grade ) ) ;
                }
                else if( "PT".equals(fields[0]) )
                {
                    String name = fields[1] ;
                    int workNumber = Integer.parseInt(fields[2]) ;
                    int grade = Integer.parseInt(fields[3]) ;
                    double hoursWorked = Double.parseDouble(fields[4]) ;
                    list.addEmployee( new PartTimeEmployee( name, workNumber, grade, hoursWorked ) ) ;
                }
                else if( "CO".equals(fields[0]) )
                {
                    String name = fields[1] ;
                    int workNumber = Integer.parseInt(fields[2]) ;
                    double monthlySalesTotal = Double.parseDouble(fields[3]) ;
                    list.addEmployee( new CommissionedEmployee( name, workNumber, new Sterling( monthlySalesTotal ) ) ) ;
                }
                else
                {
                    System.out.println("["+filename+": "+lineNr+"] Unknown type, should be PT/FT/CO.") ;
                    continue ;
                }
            }
        }
        catch(FileNotFoundException fnfe)
        {
            System.out.println("["+filename+"] File not found.") ;
        }
        catch(IOException ioe)
        {
            System.out.println("["+filename+"] I/O error.") ;
        }

        return list ;
    }

    public static void doPayroll( StaffList list )
    {
        list.sortStaffList() ;
        list.print();

        Sterling total = list.sumSalaries() ;
        total.print();
    }

    public static void main(String[] args)
    {
        if(args.length == 0)
        {
            System.out.println("Usage: java StaffMain <filename>") ;
            return ;
        }

        StaffList list = readFile(args[0]) ;
        doPayroll( list ) ;
    }
}

Good luck.
Mark
0
 

Author Comment

by:junaid_raja30
ID: 18111027
Mark, a real big thanx for all that, but Mark what the real question is that


please could you give me some advice on JAVA, like basically how to excel in it and like how to get to know everything,

what is it? Practice, or any particular books.?

Thanx
Junaid
0
 
LVL 10

Expert Comment

by:ADSLMark
ID: 18111041
Practice, practice, practice.

Think of simple applications and try to implement them, like this assignment. Think of real life problems with some sort of hierarchy in them, then make a simplified version and create an application. Reimplement the current assignment over and over, without looking at previous work.

It just requires lots of experience to excel.

Mark
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
mapBully challenge 6 93
Running Jira on Raspberry PI 2? 3 139
mockito example issue 8 38
GUI builder for Eclipse? 8 13
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now