Write an employee payroll program that uses polymorphism to calculate and print
ID: 640107 • Letter: W
Question
Write an employee payroll program that uses polymorphism to calculate and print the
weekly payroll for your company. There are three types of employees ? hourly,
salaried, and salaried plus commission. Each type of employee gets paid using a
different formula. But for all employee types, if the calculated paycheck exceeds
$1000, the actual paycheck must be decreased to $1000.
Here is the code that works but I don't know how to change the code to decreases paychecks that are over $1000, back to $1000
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Employee {
// variables
private String name;
private String socialSecurityNumber;
private static int birthdayMonth;
private static int birthdayWeek;
//load method which will be used to prompt and take and store input
public void load() {
Scanner scanner = new Scanner(System.in);
System.out.print("Name ==>");
name = scanner.nextLine();
System.out.print("Social security number ==>");
socialSecurityNumber = scanner.next();
System.out.print("Birthday month (1-12)");
birthdayMonth = scanner.nextInt();
System.out.print("Birthday bonus week (1-4)");
birthdayWeek = scanner.nextInt();
}
// if this month is the employee's birthday, a bonus of $100.00 to it.
public double getBonus() {
//Date
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
int week = 0;
int monthInteger = 0;
//Storing the date into Strings
String dateFormatted = dateFormat.format(date);
// extracting the day part from the String
String day = dateFormatted.substring(dateFormatted.length() - 2,
dateFormatted.length());
// converting the day from string to int
int dayInteger = Integer.parseInt(day);
// alot the days from 1 to 7 to week 1, 8 to 14 it is week 2, from 15 to 21 is week 3, from 22 onwards it is week 4.
if (dayInteger >= 1 && dayInteger <= 7) {
week = 1;
} else if (dayInteger >= 8 && dayInteger <= 14) {
week = 2;
} else if (dayInteger >= 15 && dayInteger <= 21) {
week = 3;
} else {
week = 4;
}
// extracting the month part from date
String month = dateFormatted.substring(5, 7);
monthInteger = Integer.parseInt(month);
// if the birthday of employee is same as system date, return 100 dollars.
if (week == birthdayWeek && monthInteger == birthdayMonth) {
return 100;
} else {
// else return 0
return 0;
}
}
public double getEarnings() {
return 0;
}
// toString() method to print object into readable form.
@Override
public String toString() {
return " employee: " + name + " social security number: "
+ socialSecurityNumber;
}
}
import java.util.Scanner;
//a subclass of Employee.java
public class Hourly extends Employee {
// variables declation
private double hourlyPay;
private double hourWorkedPastWeek;
// load method to prompt user for input and store into variables.
public void load() {
Scanner scanner = new Scanner(System.in);
System.out.print("Hourly pay ==>");
hourlyPay = scanner.nextDouble();
System.out.print("Hours worked this past week ==>");
hourWorkedPastWeek = scanner.nextDouble();
}
// getEarnings() method
//if no of hours worked is less than 40, then earning is number of hours * hourly pay
@Override
public double getEarnings() {
if (hourWorkedPastWeek < 40) {
return hourlyPay * hourWorkedPastWeek;
} else {
// if it exceeds more than 40, then for first 40 hours, it ll be number of hours * hourly pay
// and for hours more than 40, 1.5 * number of hours * hourly pay
return (hourlyPay * 40)
+ (1.5 * hourlyPay * (hourWorkedPastWeek - 40));
}
}
//to string method to print object in readable form
@Override
public String toString() {
return " paycheck: " + (getBonus() + getEarnings()) + " ";
}
}
import java.util.Scanner;
// A subclass of Employee
public class Salaried extends Employee {
// variable declaration
protected static double weeklySalary;
// load method to prompt user for input and store into variables.
public void load() {
System.out.print("Salary ==>");
Scanner scanner = new Scanner(System.in);
weeklySalary = scanner.nextDouble();
}
// return the weekly salary
@Override
public double getEarnings() {
return weeklySalary;
}
//to string method to print object in readable form
@Override
public String toString() {
return " paycheck: " + (getBonus() + getEarnings()) + " ";
}
}
import java.util.Scanner;
// A subclass of Salaried.java
public class SalariedPlusCommission extends Salaried {
private double salesDuringPastWeek;
private double commissionRate;
//load method to prompt user and store the input
public void load() {
System.out.print("Sales for this past week ==>");
Scanner scanner = new Scanner(System.in);
salesDuringPastWeek = scanner.nextDouble();
System.out
.print("Sales commission rate (fraction paid to employee) ==>");
commissionRate = scanner.nextDouble();
}
// earning is computed on the salary + weekly sales and a part of commission of weekly salary
@Override
public double getEarnings() {
double percentageOfSales = salesDuringPastWeek * commissionRate;
return percentageOfSales + weeklySalary;
}
//to string method to print object in readable form
@Override
public String toString() {
return " paycheck: " + (getBonus() + getEarnings()) + " ";
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
//class containing main () method
public class Test {
public static void main(String[] args) {
// creating a list to store all the inputs and print them
List<String> list = new ArrayList<String>();
while (true) {
System.out.println(" ");
System.out.println("Press 1 to add employee");
System.out.println("Press 2 to print PAYCHECK REPORT");
System.out.println("Press 3 to exit");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
if (choice == 3) {
System.exit(1);
} else {
switch (choice) {
case 1:// to add the employee
System.out
.println("type Hourly(1), Salaried (2), Salaried plus Commission (3)");
System.out.print("Enter 1, 2, or 3 ==>");
// input from user and on basis of that hourly, salaried and commission type of classes are called.
int input = scanner.nextInt();
Employee emp = new Employee();
//calling the load method in Employee class to enter employee details
emp.load();
if (input == 1) {
// if the choice 1 is made, load method of Hourly class is called.
Hourly hour = new Hourly();
hour.load();
// once all the details are populated in the object, the object is added into the list
list.add(emp.toString() + hour.toString());
} else if (input == 2) {
// if the choice made is 2, then object of Salaried class is made.
Salaried sal = new Salaried();
// method load is called and populated
sal.load();
// once all the details are populated in the object, the object is added into the list
list.add(emp.toString() + sal.toString());
} else if (input == 3) {
// if choice 3 is made, then object of class SalariedPlusCommission is made and populated.
SalariedPlusCommission salaryPlusCommission = new SalariedPlusCommission();
Salaried sal = new Salaried();
sal.load();
salaryPlusCommission.load();
// once all the details are populated in the object, the object is added into the list
list.add(emp.toString()
+ salaryPlusCommission.toString());
} else {
System.out.println("Invalid choice made!!!");
}
break;
case 2:
// printing the details stored in the list
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).toString());
}
}
}
}
}
}
Explanation / Answer
// PayrollSystemTest.java
// Employee hierarchy test program.
public class PayrollSystemTest
{
public static void main( String args[] )
{
// create subclass objects
SalariedEmployee salariedEmployee =
new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 );
HourlyEmployee hourlyEmployee =
new HourlyEmployee( "Karen", "Price", "222-22-2222", 16.75, 40 );
CommissionEmployee commissionEmployee =
new CommissionEmployee(
"Sue", "Jones", "333-33-3333", 10000, .06 );
BasePlusCommissionEmployee basePlusCommissionEmployee =
new BasePlusCommissionEmployee(
"Bob", "Lewis", "444-44-4444", 5000, .04, 300 );
System.out.println( "Employees processed individually: " );
System.out.printf( "%s %s: $%,.2f ",
salariedEmployee, "earned", salariedEmployee.earnings() );
System.out.printf( "%s %s: $%,.2f ",
hourlyEmployee, "earned", hourlyEmployee.earnings() );
System.out.printf( "%s %s: $%,.2f ",
commissionEmployee, "earned", commissionEmployee.earnings() );
System.out.printf( "%s %s: $%,.2f ",
basePlusCommissionEmployee,
"earned", basePlusCommissionEmployee.earnings() );
// create four-element Employee array
Employee employees[] = new Employee[ 4 ];
// initialize array with Employees
employees[ 0 ] = salariedEmployee;
employees[ 1 ] = hourlyEmployee;
employees[ 2 ] = commissionEmployee;
employees[ 3 ] = basePlusCommissionEmployee;
System.out.println( "Employees processed polymorphically: " );
// generically process each element in array employees
for ( Employee currentEmployee : employees )
{
System.out.println( currentEmployee ); // invokes toString
// determine whether element is a BasePlusCommissionEmployee
if ( currentEmployee instanceof BasePlusCommissionEmployee )
{
// downcast Employee reference to
// BasePlusCommissionEmployee reference
BasePlusCommissionEmployee employee =
( BasePlusCommissionEmployee ) currentEmployee;
double oldBaseSalary = employee.getBaseSalary();
employee.setBaseSalary( 1.10 * oldBaseSalary );
System.out.printf(
"new base salary with 10%% increase is: $%,.2f ",
employee.getBaseSalary() );
} // end if
System.out.printf(
"earned $%,.2f ", currentEmployee.earnings() );
} // end for
// get type name of each object in employees array
for ( int j = 0; j < employees.length; j++ )
System.out.printf( "Employee %d is a %s ", j,
employees[ j ].getClass().getName() );
} // end main
} // end class PayrollSystemTest
// Employee.java
// Employee abstract superclass.
public abstract class Employee
{
private String firstName;
private String lastName;
private String socialSecurityNumber;
// three-argument constructor
public Employee( String first, String last, String ssn )
{
firstName = first;
lastName = last;
socialSecurityNumber = ssn;
} // end three-argument Employee constructor
// set first name
public void setFirstName( String first )
{
firstName = first;
} // end method setFirstName
// return first name
public String getFirstName()
{
return firstName;
} // end method getFirstName
// set last name
public void setLastName( String last )
{
lastName = last;
} // end method setLastName
// return last name
public String getLastName()
{
return lastName;
} // end method getLastName
// set social security number
public void setSocialSecurityNumber( String ssn )
{
socialSecurityNumber = ssn; // should validate
} // end method setSocialSecurityNumber
// return social security number
public String getSocialSecurityNumber()
{
return socialSecurityNumber;
} // end method getSocialSecurityNumber
// return String representation of Employee object
public String toString()
{
return String.format( "%s %s social security number: %s",
getFirstName(), getLastName(), getSocialSecurityNumber() );
} // end method toString
// abstract method overridden by subclasses
public abstract double earnings(); // no implementation here
} // end abstract class Employee
// Date.java
// Date class declaration.
public class Date
{
private int month; // 1-12
private int day; // 1-31 based on month
private int year; // any year
// constructor: call checkMonth to confirm proper value for month;
// call checkDay to confirm proper value for day
public Date( int theMonth, int theDay, int theYear )
{
month = checkMonth( theMonth ); // validate month
year = theYear; // could validate year
day = checkDay( theDay ); // validate day
System.out.printf(
"Date object constructor for date %s ", this );
} // end Date constructor
// utility method to confirm proper month value
private int checkMonth( int testMonth )
{
if ( testMonth > 0 && testMonth <= 12 ) // validate month
return testMonth;
else // month is invalid
{
System.out.printf(
"Invalid month (%d) set to 1.", testMonth );
return 1; // maintain object in consistent state
} // end else
} // end method checkMonth
// utility method to confirm proper day value based on month and year
private int checkDay( int testDay )
{
int daysPerMonth[] =
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// check if day in range for month
if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
return testDay;
// check for leap year
if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||
( year % 4 == 0 && year % 100 != 0 ) ) )
return testDay;
System.out.printf( "Invalid day (%d) set to 1.", testDay );
return 1; // maintain object in consistent state
} // end method checkDay
// return a String of the form month/day/year
public String toString()
{
return String.format( "%d/%d/%d", month, day, year );
} // end method toString
} // end cla
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.