Question

C# Hey I am having trouble implementing additonal function to this assignment: Problem: Implement three IComparer classes on Employee - NameComparer, AgeComparer, and PayComparer - that allow Employee...

C#

Hey I am having trouble implementing additonal function to this assignment:

Problem:

Implement three IComparer classes on Employee - NameComparer, AgeComparer, and PayComparer - that allow Employees to be compared by the Name, Age, and Pay, respectively.

Code:


Employee.Core.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Employees
{
partial class Employee
{
// Field data.
private string empName;
private int empID;
private float currPay;
private int empAge;
private string empSSN = "";
private string empBene = "Standard";

#region Constructors

// Note use of constructor chaining.
public Employee() { }

// Creates object using name, id, and pay. Age defaults to 0 and Benefits default to Standard
public Employee(string name, int id, float pay)
: this(name, 0, id, pay)
{ }

public Employee(string name, int age, int id, float pay)
{
Name = name;
Age = age;
ID = id;
Pay = pay;
}

// Add to the Employee base class.
public Employee(string name, int age, int id, float pay, string ssn)
: this(name, age, id, pay)
{
empSSN = ssn;
}

#endregion

#region Properties
// Properties!
public string Name
{
get { return empName; }
set
{
if (value.Length > 15)
Console.WriteLine("Error! Name length exceeds 15 characters");
else
empName = value;
}
}

// We could add additional business rules to the sets of these properties,
// however there is no need to do so for this example.
public int ID
{
get { return empID; }
set { empID = value; }
}
public float Pay
{
get { return currPay; }
set { currPay = value; }
}
public int Age
{
get { return empAge; }
set { empAge = value; }
}

public string SocialSecurityNumber
{
get { return empSSN; }
}

public string CurrentPackage
{
get { return empBene; }
set { empBene = value; }
}
#endregion

#region Original benefits code

// Contain a BenefitPackage object.
protected BenefitPackage empBenefits = new BenefitPackage();

// Expose certain benefit behaviors of object.
public double GetBenefitCost()
{ return empBenefits.ComputePayDeduction(empBene); }

// Expose object through a custom property.
public BenefitPackage Benefits
{
get { return empBenefits; }
set { empBenefits = value; }
}
#endregion

#region GivePromotion related

// Used to upgrade bene
public string UpgradeBenefitPackageLevel()
{
for (int i = 0; i < empBenefits.lBenefits.Capacity - 1; i++)
{
// finds current bene position in list, and then sets to the
// next package level
if (empBenefits.lBenefits[i].Equals(empBene))
{
string npack = empBenefits.lBenefits[i + 1];
string message = empBene + " has been upgraded to " + npack;
CurrentPackage = npack;
return message;
}
}
return empBene + " is already the highest package.";
}

#endregion
}
}

&&

Employee.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Employees
{
abstract partial class Employee
{
#region Nested benefit package
// This new type will function as a contained class.
public class BenefitPackage
{
public string beneLevel = "Standard";

// Using list instead of enum
public List<string> lBenefits = new List<string>()
{
"Standard",
"Gold",
"Platinum"
};

public BenefitPackage()
{

}

// Constructor that accepts
public BenefitPackage(string packageLevel)
{
if (VarifyPackage(packageLevel))
{
beneLevel = packageLevel;
}
}

// Varify package isn't already present
protected bool VarifyPackage(string package)
{
foreach (string n in lBenefits)
{
if (n.Equals(package))
{
return true;
}
}
return false;
}

// Can insert new bene package
public void AddPackage(int position, string newpackage)
{
if (!VarifyPackage(newpackage))
{
lBenefits.Insert(position, newpackage);
}
else
{
Console.WriteLine(newpackage + " is already present");
}
}


// Assume we have other members that represent
// dental/health benefits, and so on.
public double ComputePayDeduction(string empBene)
{
switch (empBene)
{
case "Standard":
return 125.0;

case "Gold":
return 150.0;

case "Platinum":
return 200.0;

default:
return 130.0;
}
}
}
#endregion

#region Class methods
public virtual void GiveBonus(float amount)
{ Pay += amount; }

/**
* Used to give a promotion
*/
public virtual void GivePromotion()
{
Console.Write(GetName() + ": Promoted, ");
Console.WriteLine(UpgradeBenefitPackageLevel());
}

/**
* Displays employee stats
*/
public virtual void DisplayStats()
{
Console.WriteLine("Name: {0}", Name);
Console.WriteLine("ID: {0}", ID);
Console.WriteLine("Age: {0}", Age);
Console.WriteLine("Pay: {0}", Pay);
Console.WriteLine("SSN: {0}", SocialSecurityNumber);
Console.WriteLine("Benefit Package Level: {0}", CurrentPackage);
Console.WriteLine("EmpBenefits: {0}", GetBenefitCost());
}

#endregion


#region Traditional Get / Set method
// Accessor (get method)
public string GetName()
{
return empName;
}

// Mutator (set method)
public void SetName(string name)
{
// Do a check on incoming value
// before making assignment.
if (name.Length > 15)
Console.WriteLine("Error! Name must be less than 15 characters!");
else
empName = name;
}

public override string ToString()
{
return GetName();
}
#endregion
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

BenefitPackage.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Employees
{
  
    // This new type will function as a contained class.
    class BenefitPackage
    {
        // Assume we have other members that represent
        // dental/health benefits, and so on.
        public double ComputePayDeduction()
        {
            return 125.0;
        }
    }
  
}


Employee.Core.cs

using System;

namespace Employees
{
    public partial class Employee
    {
        // Field data.
        private string empName;
        private int empID;
        private float currPay;
        private int empAge;
        private string empSSN = "";

        #region Constructors
        // Note use of constructor chaining.
        public Employee() { }
        public Employee(string name, int id, float pay)
          : this(name, 0, id, pay)
        { }
        public Employee(string name, int age, int id, float pay)
        {
            Name = name;
            Age = age;
            ID = id;
            Pay = pay;
        }

        // Add to the Employee base class.
        public Employee(string name, int age, int id, float pay, string ssn)
            :this(name, age, id, pay)
        {
            empSSN = ssn;
        }
        #endregion

        #region Properties
        // Properties!
        public string Name
        {
            get { return empName; }
            set
            {
                if (value.Length > 15)
                    Console.WriteLine("Error! Name length exceeds 15 characters");
                else
                    empName = value;
            }
        }

        // We could add additional business rules to the sets of these properties,
        // however there is no need to do so for this example.
        public int ID
        {
            get { return empID; }
            set { empID = value; }
        }
        public float Pay
        {
            get { return currPay; }
            set { currPay = value; }
        }
        public int Age
        {
            get { return empAge; }
            set { empAge = value; }
        }

        public string SocialSecurityNumber
        {
            get { return empSSN; }
        }
        #endregion

        // Contain a BenefitPackage object.
        protected BenefitPackage empBenefits = new BenefitPackage();

        // Expose certain benefit behaviors of object.
        public double GetBenefitCost()
        { return empBenefits.ComputePayDeduction(); }

        // Expose object through a read-only property.
        public BenefitPackage Benefits
        {
            get { return empBenefits; }
        }
    }
}

Employee.cs

using System;
using System.Collections;

namespace Employees
{
    abstract public partial class Employee
    {
        #region Nested benefit packages
        public class BenefitPackage
        {
            public enum BenefitPackageLevel
            {
                Standard, Gold, Platinum
            }

            // Assume we have other members that represent
            // dental/health benefits, and so on.
            public double ComputePayDeduction()
            {
                return 125.0;
            }
        }
        #endregion

        #region Class methods
        public virtual void GiveBonus(float amount)
        { Pay += amount; }

        public virtual void DisplayStats()
        {
            Console.WriteLine("Name: {0}", Name);
            Console.WriteLine("ID: {0}", ID);
            Console.WriteLine("Age: {0}", Age);
            Console.WriteLine("Pay: {0:C}", Pay);
            Console.WriteLine("SSN: {0}", SocialSecurityNumber);
        }
        #endregion

        #region Traditional Get / Set method
        // Accessor (get method)
        public string GetName()
        {
            return empName;
        }

        // Mutator (set method)
        public void SetName(string name)
        {
            // Do a check on incoming value
            // before making assignment.
            if (name.Length > 15)
                Console.WriteLine("Error! Name must be less than 15 characters!");
            else
                empName = name;
        }
       #endregion

       #region Employee sort oders
       // Sort employees by name.
       private class NameComparer : IComparer
       {
           // Compare the name of each object.
           int IComparer.Compare(object o1, object o2)
           {
               Employee t1 = o1 as Employee;
               Employee t2 = o2 as Employee;
               if (t1 != null && t2 != null)
                   return String.Compare(t1.Name, t2.Name);
               else
                   throw new ArgumentException("Parameter is not an Employee!");
           }
       }

       // Sort by age
       private class AgeComparer : IComparer
       {
           // Compare the Age of each object.
           int IComparer.Compare(object o1, object o2)
           {
               Employee t1 = o1 as Employee;
               Employee t2 = o2 as Employee;
               if (t1 != null && t2 != null)
                   return t1.Age.CompareTo(t2.Age);
               else
                   throw new ArgumentException("Parameter is not an Employee!");
           }
       }
      
        // Sort By pay
       private class PayComparer : IComparer
       {
           // Compare the Pay of each object.
           int IComparer.Compare(object o1, object o2)
           {
               Employee t1 = o1 as Employee;
               Employee t2 = o2 as Employee;
               if (t1 != null && t2 != null)
                   return t1.Pay.CompareTo(t2.Pay);
               else
                   throw new ArgumentException("Parameter is not an Employee!");
           }
       }

       // Static, read-only properties to return Employee Name, Age, or Pay comparers
       public static IComparer SortByName { get; } = new NameComparer();
       public static IComparer SortByPay { get; } = new PayComparer();
       public static IComparer SortByAge { get; } = new AgeComparer();

       #endregion
   }
}

Manager.cs

using System;
using System.Collections;

namespace Employees
{
    // Managers need to know their number of stock options and reports
    public class Manager : Employee, IEnumerable
    {
        #region constructors
        public Manager() { }

        public Manager(string fullName, int age, int empID,
                       float currPay, string ssn, int numbOfOpts)
          : base(fullName, age, empID, currPay, ssn)
        {
            // This property is defined by the Manager class.
            StockOptions = numbOfOpts;
        }
       #endregion

       #region Constants, data members and properties
        // Add a private member for reports
       public const int MaxReports = 5;
       private static Employee NullEmp = new Manager();
       private Employee[] _reports = { NullEmp, NullEmp, NullEmp, NullEmp, NullEmp };

        // Stock options unique to Managers
       public int StockOptions { get; set; }
        #endregion

        #region Exceptions
        // Exception raised when adding more than MaxReports to a Manager
        [System.Serializable]
        public class TooManyReportsException : ApplicationException
        {
            // Standard exception constructors
            public TooManyReportsException() {}
            public TooManyReportsException(string message)
                : base(message) {}
            public TooManyReportsException(string message, Exception inner)
                : base(message, inner) {}
            protected TooManyReportsException(System.Runtime.Serialization.SerializationInfo info,
                                  System.Runtime.Serialization.StreamingContext context)
                : base(info, context) {}
        }
       #endregion

       #region Class Methods
        // Enumerate reports for Manager
       IEnumerator IEnumerable.GetEnumerator()
       {
            // Return non-null reports
            foreach (Employee emp in _reports) {
                if (emp != NullEmp) yield return emp;
            }
       }

        // Enumerate reports, sorted by Employee Name, Age, and Pay
       public IEnumerable ReportsByName() { return GetReports(Employee.SortByName); }
       public IEnumerable ReportsByAge() { return GetReports(Employee.SortByAge); }
       public IEnumerable ReportsByPay() { return GetReports(Employee.SortByPay); }

        // Enumerator to return reports in passed sort order
        private IEnumerable GetReports(IComparer sortOrder = null)
        {
            // Sort reports if sort order non-null
            if (sortOrder != null) Array.Sort(_reports, sortOrder);

            // Enumerate reports in specified order
           foreach (Employee emp in this) yield return emp;
       }

       // Override GiveBonus to change stock options for Manager
       public override void GiveBonus(float amount)
        {
            base.GiveBonus(amount);
            Random r = new Random();
            StockOptions += r.Next(500);
        }

        // Methods for adding/removing reports
        public virtual void AddReport(Employee report)
        {
            int emptyPos = Array.IndexOf(_reports, NullEmp);

            // Array full - no empty positions
            if (emptyPos < 0)
            {
                // Raise excepction for too many reports
               Exception ex = new TooManyReportsException(
                    string.Format("Manager already has {0} reports.", MaxReports));

                // Add Manager custom data dictionary
                ex.Data.Add("Manager", this.Name);

                // Build report string and add to custom data dictionary
               string reports = "";
               foreach (Employee emp in this) reports += emp.Name + " ";
                ex.Data.Add("Reports", reports);

                // Finally, add report that failed to be added, and throw exception
               ex.Data.Add("New Report", report.Name);
               throw ex;
            }

            // Only add report if not already a report and not same as this
            else if (Array.IndexOf(_reports, report) < 0 && this != report)
            {
                // Put Employee in empty position
                _reports.SetValue(report, emptyPos);
            }
        }

        public virtual void RemoveReport(Employee emp)
        {
            // See if the passed employee is a report
            int pos = Array.IndexOf(_reports, emp);

            if (pos >= 0)
            {
                _reports.SetValue(NullEmp, pos);
            }
        }

        // Display Manager with stock options and list of reports
        public override void DisplayStats()
        {
            base.DisplayStats();
            Console.WriteLine("Stock Options: {0:N0}", StockOptions);

            // Print out reports on a single line
            Console.Write("Reports: ");
           foreach (Employee emp in this)
               Console.Write("{0} ", emp.Name);
           Console.WriteLine();
        }
        #endregion
    }
}

Program.cs

using System;
using System.Collections;

namespace Employees
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("***** Assignment 4: Employee Reports *****\n");

            // Create Employees
            Manager chucky = new Manager("Chucky", 50, 92, 100000, "333-23-2322", 9000);
           Manager mary   = new Manager("Mary", 54, 90, 200000, "121-12-1211", 9500);
           SalesPerson fran = new SalesPerson("Fran", 43, 93, 80000, "932-32-3232", 31);
            SalesPerson bob = new SalesPerson("Bob", 31, 94, 120000, "334-24-2422", 30);
            PTSalesPerson sally = new PTSalesPerson("Sally", 32, 95, 30000, "913-43-4343", 10);
            PTSalesPerson sam = new PTSalesPerson("Sam", 33, 96, 20000, "525-76-5030", 20);
           PTSalesPerson mike = new PTSalesPerson("Mike", 45, 91, 15000, "229-67-7898", 30);

           // Employee list
           Employee[] emps = { chucky, mary, fran, bob, sally, sam, mike };

            // Add reports
            try
            {
                mary.AddReport(fran);
                mary.AddReport(mike);
                chucky.AddReport(bob);
                chucky.AddReport(sally);
                chucky.AddReport(sam);
                mary.RemoveReport(fran);
                mary.RemoveReport(chucky);
                chucky.AddReport(fran);
                chucky.AddReport(mike);
                chucky.AddReport(mary);
            }
           catch(Manager.TooManyReportsException e)
           {
               Console.WriteLine("*** Error! ***");
               Console.WriteLine("Source: {0}", e.Source);
               Console.WriteLine("Method: {0}", e.TargetSite);
               Console.WriteLine("Message: {0}", e.Message);
               Console.WriteLine("Custom Data:");
               foreach (DictionaryEntry de in e.Data)
                   Console.WriteLine("-> {0}: {1}", de.Key, de.Value);

           }

            Console.WriteLine("\nDisplay Managers\n");
           mary.DisplayStats();
            Console.WriteLine();
            chucky.RemoveReport(sam); // Remove a report for testing
            chucky.DisplayStats();
            Console.Write("Reports by Name: ");
            foreach (Employee emp in chucky.ReportsByName())
                Console.Write("{0} ", emp.Name);
           Console.Write("\nReports by Age: ");
           foreach (Employee emp in chucky.ReportsByAge())
               Console.Write("{0}-{1} ", emp.Age, emp.Name);
           Console.Write("\nReports by Pay: ");
           foreach (Employee emp in chucky.ReportsByPay())
                Console.Write("{0:C}-{1} ", emp.Pay, emp.Name);
            Console.WriteLine();

           Console.ReadLine();
        }
    }
}

SalesPerson.cs

using System;
using System.Collections;

namespace Employees
{
    // Salespeople need to know their number of sales.
    class SalesPerson : Employee
    {
        #region constructors
        public SalesPerson() { }

        // As a general rule, all subclasses should explicitly call an appropriate
        // base class constructor.
        public SalesPerson(string fullName, int age, int empID,
          float currPay, string ssn, int numbOfSales)
          : base(fullName, age, empID, currPay, ssn)
        {
            // This belongs with us!
            SalesNumber = numbOfSales;
        }
        #endregion

        public int SalesNumber { get; set; }

        // A salesperson's bonus is influenced by the number of sales.
        public override sealed void GiveBonus(float amount)
        {
            int salesBonus = 0;
            if (SalesNumber >= 0 && SalesNumber <= 100)
                salesBonus = 10;
            else
            {
                if (SalesNumber >= 101 && SalesNumber <= 200)
                    salesBonus = 15;
                else
                    salesBonus = 20;
            }
            base.GiveBonus(amount * salesBonus);
        }

        public override void DisplayStats()
        {
            base.DisplayStats();
            Console.WriteLine("Number of sales: {0:N0}", SalesNumber);
        }
    }
}

PTSalesEmployee.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Employees
{
    sealed class PTSalesPerson : SalesPerson
    {
        public PTSalesPerson(string fullName, int age, int empID,
                             float currPay, string ssn, int numbOfSales)
          : base(fullName, age, empID, currPay, ssn, numbOfSales)
        {
        }
        // Assume other members here...
    }
}

Add a comment
Know the answer?
Add Answer to:
C# Hey I am having trouble implementing additonal function to this assignment: Problem: Implement three IComparer classes on Employee - NameComparer, AgeComparer, and PayComparer - that allow Employee...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Hey guys I am having trouble getting my table to work with a java GUI if...

    Hey guys I am having trouble getting my table to work with a java GUI if anything can take a look at my code and see where I am going wrong with lines 38-49 it would be greatly appreciated! Under the JTableSortingDemo class is where I am having erorrs in my code! Thanks! :) import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.List; import javax.swing.*; public class JTableSortingDemo extends JFrame{ private JTable table; public JTableSortingDemo(){ super("This is basic sample for your...

  • Hi, I am writing Java code and I am having a trouble working it out. The...

    Hi, I am writing Java code and I am having a trouble working it out. The instructions can be found below, and the code. Thanks. Instructions Here are the methods needed for CIS425_Student: Constructor: public CIS425_Student( String id, String name, int num_exams ) Create an int array exams[num_exams] which will hold all exam grades for a student Save num_exams for later error checking public boolean addGrade( int exam, int grade ) Save a grade in the exams[ ] array at...

  • Previous class code: 1) Employee.java ------------------------------------------------------------------------------- /** * */ package main.webapp; /** * @author sargade *...

    Previous class code: 1) Employee.java ------------------------------------------------------------------------------- /** * */ package main.webapp; /** * @author sargade * */ public class Employee { private int empId; private String empName; private Vehicle vehicle; public Double calculatePay() { return null; } /** * @return the empId */ public int getEmpId() { return empId; } /** * @param empId * the empId to set */ public void setEmpId(int empId) { this.empId = empId; } /** * @return the empName */ public String getEmpName() { return...

  • Hey I am having trouble with this problem in C++: The first race is tomorrow! You...

    Hey I am having trouble with this problem in C++: The first race is tomorrow! You are provided a list of race entries in the following form: vector<string> entryList = { "42, Vance Cardoza", "55, Vanessa Pandara", "36, Gaston Carlton", "99, Rich Diesel", "10, Euler Bustamente" }; In your main() function instantiate a Race object. Use a C++ iterator to walk through the entries in the list above, parse out each car number and driver name and add them to...

  • JAVA: How do I output all the data included for each employee? I can only get...

    JAVA: How do I output all the data included for each employee? I can only get it to output the name, monthly salary and annual salary, but only from the Employee.java file, not Salesman.java or Executive.java. Employee.java package project1; public class Employee { private String name; private int monthlySalary; public Employee(String name, int monthlySalary) { this.name = name; this.monthlySalary = monthlySalary; } public int getAnnualSalary() { int totalPay = 0; totalPay = 12 * monthlySalary; return totalPay; } public String...

  • Hi, I am having trouble solving the constructor, it requires to ArrayList marks to be a...

    Hi, I am having trouble solving the constructor, it requires to ArrayList marks to be a deep copy of the instance variable. I have also provided the J-Unit test I have been provided. import java.util.*; public class GradebookEntry { private String name; private int id; private ArrayList<Double> marks; /** * DO NOT MODIFY */ public String toString() { String result = name+" (ID "+id+")\t"; for(int i=0; i < marks.size(); i++) { /** * display every mark rounded off to two...

  • I need help converting the following two classes into one sql table package Practice.model; impor...

    I need help converting the following two classes into one sql table package Practice.model; import java.util.ArrayList; import java.util.List; import Practice.model.Comment; public class Students {          private Integer id;    private String name;    private String specialties;    private String presentation;    List<Comment> comment;       public Students() {}       public Students(Integer id,String name, String specialties, String presentation)    {        this.id= id;        this.name = name;        this.specialties = specialties;        this.presentation = presentation;        this.comment = new ArrayList<Commment>();                  }       public Students(Integer id,String name, String specialties, String presentation, List<Comment> comment)    {        this.id= id;        this.name...

  • Java Do 72a, 72b, 72c, 72d. Code & output required. public class Employee { private int...

    Java Do 72a, 72b, 72c, 72d. Code & output required. public class Employee { private int id; private String name; private int sal; public Employee(int id, String name, int sal) { super(); this.id = id; this.name = name; this.sal = sal; } public int getid) { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; public void setName(String name) { this.name = name; } public int get Sall) { return sal;...

  • Please answer the following question with Java Modify the Employee and ProductionWorker classes provided below so...

    Please answer the following question with Java Modify the Employee and ProductionWorker classes provided below so they throw exceptions when the following errors occur. - The Employee class should throw an exception named InvalidEmployeeNumber when it receives an employee number that is less than 0 or greater than 9999. - The ProductionWorker class should throw an exception named InvalidShift when it receives an invalid shift. - The ProductionWorker class should thrown anexception named InvalidPayRate when it receives a negative number...

  • //*Manager.java*// public interface Manager { public void handleCrisis(); } _________________________________________________________ /**Employee.java**/ Public abstract class Employee {...

    //*Manager.java*// public interface Manager { public void handleCrisis(); } _________________________________________________________ /**Employee.java**/ Public abstract class Employee { protected final String name; protected final int id; public Employee(String empName, int empId) { name = empName; id = empId; } public Employee() { name = generatedNames[lastGeneratedId]; id = lastGeneratedId++; } public String getName() { return name; } public int getId() { return id; } //returns true if work was successful. otherwise returns false (crisis) public abstract boolean work(); public String toString() { return...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT