So what this program is suppose to do is grab input from the keyboard for the id, hours and wage. It is then going to calculate the overtime pay, regular pay and gross pay. After the calculations, id, hours, wage, overtime pay, regular pay and gross pay are supposed to be calculated have to be printed to the output.
Also the properties and the behaviours of the employee are suppose to be in the employee class.
But when I want to print the toString method, Regular Pay, Overtime pay and gross pay comes out as zeros. Any idea why?
main method:
public class FinalExam
{ // begin class
public static void main(String[] args)
{ // begin main
// ********** DECLARATION OF CONSTANTS **********
// ********** DECLARATION OF VARIABLES **********
String strout; // output string (toString)
int ID; // employee's id number
int Hours; // employee's hours worked
double Wage; // employee's wage per hour
// ********** CREATE OBJECTS **********
ArrayList<Employee> employeeInfo = new ArrayList(); // list of all employee's properties/objects
// ********** CREATE INPUT STREAMS **********
Scanner keyboard = new Scanner(System.in); // create a Scanner object for keyboard input.
// ********** GET INPUT **********
// get the employee's ID
System.out.println("\nEnter your employee ID.");
ID = keyboard.nextInt(); //get the input and set it to the local varaible ID
Employee employee = new Employee(ID); // pass your id
//System.out.println("Employee ID: " + ID);
// get the employee's hours worked
System.out.println("\nEnter the amount of hours you worked this week.");
Hours = keyboard.nextInt(); //get the input and set it to the local varaible HoursWorked
employee.setHours(Hours); // pass your hours
//System.out.println("Hours worked: " + Hours);
// get the employee's wage
System.out.println("\nEnter your wage.");
Wage = keyboard.nextDouble(); //get the input and set it to the local varaible Wage
employee.setWage(Wage); // pass your wage
//System.out.println("Employee wage: " + Wage);
employeeInfo.add(employee); // add it to the list of course
// ********** OUTPUT **********
System.out.println("\n\n" + employeeInfo.toString());
} // end main
} // end class
then the Employee class:
public class Employee
{ // begin class
// *********** CLASS VARIABLES **********
// *********** CLASS CONSTANTS **********
private static int MAXHOURS = 40; // maximum hours before overime
private static double OTRATE = 1.5; // overtime is one and a half
// ********** INSTANCE VARIABLES **********
private int ID; // employee's id
private int Hours; // number of hours worked
private double Wage; // pay per hour
private double RegularPay; // regular pay
private int OverHours; // number of overtime hours worked
private double OverPay; // overtime pay
private double GrossPay; // gross pay
// ********** CREATE INPUT STREAMS **********
DecimalFormat df1 = new DecimalFormat ("#####.00"); // to get two decimal places at the end of the numbers
// ********** CONSTRUCTORS ***********
public Employee(int IDnumber)
{ // begin initialized constructor
ID = IDnumber; // set ID to ID number
} // end initialized constructor
// ********** ACCESSORS **********
public int getID()
{ // begin getID
return ID;
} // end getID
public void setWage(double HourlyWage)
{ // begin setWage
Wage = HourlyWage;
} // end setWage
public double getWage()
{ // begin getWage
return Wage;
} // end getWage
public void setHours(int hoursWorked)
{ // begin setHours
Hours = hoursWorked;
} // end setHours
public double getHours()
{ // begin getHours
return Hours;
} // end getHours
// ********** MUTATORS **********
public double getOverPay()
{ // begin getOverPay
if (Hours > MAXHOURS)
{ // begin if hours worked is bigger than MAXHOURS
OverHours = Hours - MAXHOURS;
OverPay = OverHours * Wage * OTRATE;
} // end if hours worked is bigger than MAXHOURS
else
OverPay = 0;
return OverPay;
} // end getOverPay
public double getRegularPay()
{ // begin getRegularPay
return MAXHOURS * Wage;
} // end getRegularPay
public double getGrossPay()
{ // begin getGrossPay
return RegularPay + OverPay;
} // end getGrossPay
public String toString() // overrides the toString method inherited from object
{ // begin toString
String strout = "\nId \t\t Hours \t\t Rate \t\t Regular Pay \t Overtime Pay \t Gross Pay\n";
strout += ID + "\t " + Hours + "\t\t\t $" + (df1.format(Wage)) + "\t\t $" + (df1.format(RegularPay)) + "\t\t\t $" + (df1.format(OverPay)) + "\t\t\t $" + (df1.format(GrossPay));
// df1.format(double) allows me two decimal places
return strout;
} // end toString
} // end class
You are using OvertimePay, GrossPay and RegularPay without using their getters, and these properties haven't been initilizated. You should call the getters.
import java.text.DecimalFormat;
public class Employee
{ // begin class
// *********** CLASS VARIABLES **********
// *********** CLASS CONSTANTS **********
private static int MAXHOURS = 40; // maximum hours before overime
private static double OTRATE = 1.5; // overtime is one and a half
// ********** INSTANCE VARIABLES **********
private int ID; // employee's id
private int Hours; // number of hours worked
private double Wage; // pay per hour
private double RegularPay; // regular pay
private int OverHours; // number of overtime hours worked
private double OverPay; // overtime pay
private double GrossPay; // gross pay
// ********** CREATE INPUT STREAMS **********
DecimalFormat df1 = new DecimalFormat ("#####.00"); // to get two decimal places at the end of the numbers
// ********** CONSTRUCTORS ***********
public Employee(int IDnumber)
{ // begin initialized constructor
ID = IDnumber; // set ID to ID number
} // end initialized constructor
// ********** ACCESSORS **********
public int getID()
{ // begin getID
return ID;
} // end getID
public void setWage(double HourlyWage)
{ // begin setWage
Wage = HourlyWage;
} // end setWage
public double getWage()
{ // begin getWage
return Wage;
} // end getWage
public void setHours(int hoursWorked)
{ // begin setHours
Hours = hoursWorked;
} // end setHours
public double getHours()
{ // begin getHours
return Hours;
} // end getHours
// ********** MUTATORS **********
public double getOverPay()
{ // begin getOverPay
if (Hours > MAXHOURS)
{ // begin if hours worked is bigger than MAXHOURS
OverHours = Hours - MAXHOURS;
OverPay = OverHours * Wage * OTRATE;
} // end if hours worked is bigger than MAXHOURS
else
OverPay = 0;
return OverPay;
} // end getOverPay
public double getRegularPay()
{ // begin getRegularPay
return MAXHOURS * Wage;
} // end getRegularPay
public double getGrossPay()
{ // begin getGrossPay
return getRegularPay() + OverPay;
} // end getGrossPay
public String toString() // overrides the toString method inherited from object
{ // begin toString
String strout = "\nId \t\t Hours \t\t Rate \t\t Regular Pay \t Overtime Pay \t Gross Pay\n";
strout += ID + "\t " + Hours + "\t\t\t $" + (df1.format(Wage)) + "\t\t $" + (df1.format(getRegularPay())) + "\t\t\t $" + (df1.format(getOverPay())) + "\t\t\t $" + (df1.format(getGrossPay()));
// df1.format(double) allows me two decimal places
return strout;
} // end toString
} // end class
You are not printing the state of the employee object but rather the list employeeinfo. You need to iterate over the list and print each employee:
for(Employee e : employeeInfo) {
System.out.println(e.toString());
}
Atleast give me a 1-up for the killer toString method:
import java.util.ArrayList;
import java.util.Scanner;
public class FinalExam
{
public static void main(String[] args)
{
FinalExam finalExam = new FinalExam();
finalExam.run();
}
void run()
{
Employee emp = new Employee();
ArrayList<Employee> list = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.print('\n' + "your employee id: ");
emp.setId(scan.nextInt());
System.out.print('\n' + "hours you worked: ");
emp.setHours(scan.nextInt());
System.out.print('\n' + "your wage:");
emp.setWage(scan.nextDouble());
list.add(emp);
scan.close();
System.out.println(emp.toString());
}
class Employee
{
final private int MAXHOURS = 40;
final private double OTRATE = 1.5;
private int id;
private int hours;
private double wage;
void setId(int id) { this.id = id; }
int getId() { return id; }
void setHours(int hours) { this.hours = hours; }
int getHours() { return hours; }
void setWage(double wage) { this.wage = wage; }
double getWage() { return wage; }
#Override
public String toString()
{
double payRegular, payOvertime,
payGross =
(payRegular = hours > MAXHOURS ? (MAXHOURS * wage) : (hours * wage)) +
(payOvertime = hours > MAXHOURS ? (hours - MAXHOURS) * (wage * OTRATE) : 0);
StringBuilder string = new StringBuilder(500);
string.append("\n");
string.append(
String.format("%10s %10s %10s %15s %15s %15s",
"Id", "Hours", "Rate", "Regular Pay", "Overtime Pay", "Gross Pay"));
string.append("\n");
string.append(
String.format("%10s %10s %10s %15s %15s %15s",
id, hours, wage, payRegular, payOvertime, payGross));
string.trimToSize();
return string.toString();
}
}
}
Related
Not actually sure what's wrong, just that at line 81 my scan object is skipped and then the program continues with no clear attempt to read anything, thoughts on what's wrong? btw working in eclipse
import java.util.*;
public class Hospital
{
//--- Instance Variables
private Patient patient;
private Scanner scan;
private double totalPrivateRoomCharges;
private double totalSemiPrivateRoomCharges;
private double totalWardRoomCharges;
private double totalTelephoneCharges;
private double totalTelevisionCharges;
private double totalReceipts;
//--- Constructors
public Hospital()
{
scan = new Scanner(System.in);
totalPrivateRoomCharges = 0;
totalSemiPrivateRoomCharges = 0;
totalWardRoomCharges = 0;
totalTelephoneCharges = 0;
totalTelevisionCharges = 0;
totalReceipts = 0;
mainMenu();
}
//--- Methods
public void mainMenu()
{
int ans = 0;
do
{
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Main Menu");
System.out.println();
System.out.println("1) Enter Patient Billing Information");
System.out.println("2) Print Daily Summary Report");
System.out.println("3) Exit");
System.out.println();
System.out.print("Selection: ");
ans = scan.nextInt();
System.out.println();
if(ans == 1)
{
patientBillingInfo();
}
if(ans == 2)
{
printSummaryReport();
}
}
while(ans != 3);
}
// precondition: none
// postcondition: displays a menu that allows the user to enter a patient's
// billing info which includes the patient's name, the number of days the
// patient stayed in the hospital, and the type of room
// (private, semi-private, ward).
// Once the patient info is retrieved a patient object is created and a
// billing report is generated that includes the patient's name, length
// of stay, and the charges incurred including the bill total.
// The totals that are used to print the hospitals daily summary report
// are updated.
public void patientBillingInfo()
{
String name = "";
int days = 0;
String room = "";
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Patient Billing Query");
System.out.println();
System.out.println("Enter Patient Name: ");
here the scan object seems to be completely skipped and dose not read at all just moves to the next line and continues.
name = scan.nextLine(); //getting skiped
System.out.println("Enter number of days in Hospital: ");
days = scan.nextInt();
System.out.println("Enter Room type(P, S, W): ");
room = scan.next();
System.out.println();
System.out.println();
if(!((room.equalsIgnoreCase("P")) || (room.equalsIgnoreCase("S")) || (room.equalsIgnoreCase("W"))))
{
System.out.println("Incorect room information");
System.out.println("Please enter P, S, or W for room selection");
System.out.println();
patientBillingInfo();
}
else
{
if(room.equalsIgnoreCase("P"))
totalPrivateRoomCharges += 1*days;
if(room.equalsIgnoreCase("S"))
totalSemiPrivateRoomCharges += 1*days;
if(room.equalsIgnoreCase("W"))
totalWardRoomCharges += 1*days;
totalTelephoneCharges += 1*days;
totalTelevisionCharges += 1*days;
patient = new Patient(name, days,room);
}
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Patient Billing Statement");
System.out.println();
System.out.println("Patient's name: " + patient.getName());
System.out.println("Number of days in Hospital: " + patient.getDays());
System.out.println();
System.out.println("Room charge $ " + patient.getRoomCharge());
System.out.println("Telephone charge $ " + patient.getTelephoneCharge());
System.out.println("Television charge $ " + patient.getTelevisionCharge());
System.out.println();
System.out.println("Total charge $ " +patient.getTotalCharge());
System.out.println();
System.out.println();
mainMenu();
}
// precondition: none
// postcondition: a summary report is printed that includes the daily total
// room charges for each type of room, the daily total telephone charges,
// and the daily total television charges. The report also includes the
// total receipts for the day.
public void printSummaryReport()
{
double tPRC = 225.0*totalPrivateRoomCharges;
double tSPRC = 165.0*totalSemiPrivateRoomCharges;
double tWRC = 95.0*totalWardRoomCharges;
double tTpC = 1.75*totalTelephoneCharges;
double tTvC = 3.50*totalTelevisionCharges;
double tR = tPRC+tSPRC+tWRC+tTpC+tTvC;
System.out.println(" Community Hospital");
System.out.println();
System.out.println(" Daily Billing Summary");
System.out.println();
System.out.println("Room Charges");
System.out.println(" Private: $" + tPRC);
System.out.println(" Semi-Private: $" + tSPRC);
System.out.println(" Ward: $" + tWRC);
System.out.println("Telephone Charges: $" + tTpC);
System.out.println("Telvision Charges: $" + tTvC);
System.out.println();
System.out.println("Total Receipts: $" + tR);
System.out.println();
}
}
edit: so it just occurred to me that maybe just maybe the rest of the code that this goes with might be useful dunno why I didn't think about this sooner but here's the rest
the class that actually runs
public class Administrator
{
public static void main(String[] args)
{
Hospital hospital = new Hospital();
}
}
and the class that works the patient info
public class Patient
{
//--- Constants
public final double PRIVATE = 225.00;
public final double SEMI = 165.00;
public final double WARD = 95.00;
public final double TELEPHONE = 1.75;
public final double TELEVISION = 3.50;
//--- Instance Variables
private String name;
private String roomType;
private int days;
//--- Constructors
public Patient(String n, int d, String rT)
{
name = n;
days = d;
roomType = rT;
}
//--- Methods
// precondition: none
// postcondition: returns the patient name
public String getName()
{
return name;
}
// precondition: none
// postcondition: returns the length of stay in days
public int getDays()
{
return days;
}
// precondition: none
// postcondition: returns the room type ("P", "S", "W")
public String getRoomType()
{
return roomType;
}
// precondition: none
// postcondition: returns the room charge which is dependant upon
// the room type and the length of stay.
public double getRoomCharge()
{
double charge = 0;
if(getRoomType().equalsIgnoreCase("P"))
charge = 225.00*getDays();
if(getRoomType().equalsIgnoreCase("S"))
charge = 165.00*getDays();
if(getRoomType().equalsIgnoreCase("W"))
charge = 95.00*getDays();
return charge;
}
// precondition: none
// postcondition: returns the telephone charge which is dependant upon
// the length of stay
public double getTelephoneCharge()
{
double charge = 1.75*getDays();
return charge;
}
// precondition: none
// postcondition: returns the television charge which is dependant upon
// the length of stay
public double getTelevisionCharge()
{
double charge = 3.50*getDays();
return charge;
}
// precondition: none
// postcondition: returns the total charge which is the sum
// of the room charge, telephone charge, and television charge.
public double getTotalCharge()
{
double charge = getRoomCharge()*getTelephoneCharge()+getTelevisionCharge();
return charge;
}
}
really don't know why it didn't occur to me sooner to do this but whatever live and lern right
You could simply scan a line and then parse it as the integer for Integer values.
so for reading integers instead of
val=scan.nextInt()
you could use
String strVal = scan.nextLine();
try {
val = Integer.parseInt(strVal);
} catch (NumberFormatException e) {
//maybe try again, or break the code ... or proceed as you wish.
}
this is because the nextInt() does not take the "Enter" key into account, and when you press enter after the nextInt() the int is read into the variable expecting nextInt() and the "Return" Key is accepted by the nextLine() which results in an empty line being read into the variable.
In public void mainMenu() you need to add scan.nextLine(); after ans = scan.nextInt(); in order to clear the rest of the input buffer.
ans = scan.nextInt();
scan.nextLine(); // <----- Add this line here
I am trying to get the right total sales output, I keep on getting 0.0 instead of the appropriate 400 and 950 for the first and second employee.
I think my problem is in the Commission class with the overwritten pay method
The overridden pay method in Commission must call the pay method from the parent class from Hourly to compute the pay for hours worked then add to that the pay from commission on sales(totals sales times the commission rate) The total sales should be reset to 0 after the payment is calculated. –
public class Commission extends Hourly
{
double total_sales;
double commission_rate;
public Commission(String name, String address, String phone,
String soc_sec_number, double rate,double commission_rate)
{
super( name, address, phone,
soc_sec_number, rate);
// set commission rate
commission_rate = 0.02;
}
public void addSales (double sales)
{
total_sales += sales;
}
public double pay()
{
double payment = super.pay(); // call the method of the parent
// add other code
payment = payment + (total_sales * commission_rate);
total_sales = 0.0;
return payment;
}
public String toString()
{
return super.toString() + "\nTotalSales: " + total_sales;
}
}
Hourly, the parent class with the pay method
// ********************************************************************
// Hourly.java Java Foundations
//
// Represents an employee that gets paid by the hour
// ********************************************************************
public class Hourly extends Employee
{
private int hours_worked;
// -------------------------------------------------------------------------
// Constructor: Sets up this hourly employee using the specified information
// -------------------------------------------------------------------------
public Hourly(String name, String address, String phone,
String soc_sec_number, double rate)
{
super(name, address, phone, soc_sec_number, rate);
hours_worked = 0;
}
// -----------------------------------------------------
// Adds the specified number of hours to this employee's
// accumulated hours
// -----------------------------------------------------
public void addHours(int more_hours)
{
hours_worked += more_hours;
}
// -----------------------------------------------------
// Computes and returns the pay for this hourly employee
// -----------------------------------------------------
public double pay()
{
double payment = pay_rate * hours_worked;
hours_worked = 0;
return payment;
}
// ----------------------------------------------------------
// Returns information about this hourly employee as a string
// ----------------------------------------------------------
public String toString()
{
return super.toString() + "\nCurrent hours: " + hours_worked;
}
}
and staff where all the information is stored
// ********************************************************************
// Staff.java Java Foundations
//
// Represents the personnel staff of a particular business
// ********************************************************************
import java.text.DecimalFormat;
public class Staff
{
private static DecimalFormat fmt = new DecimalFormat("0.00");
private StaffMember[] staff_list =
{
new Executive ("Tony", "123 Main Line", "555-0469", "123-45-6789", 2423.07),
new Employee ("Paulie", "456 Off Line", "555-0101", "987-65-4321", 1246.15),
new Employee ("Vito", "789 Off Rocker", "555-0000", "010-20-3040", 1169.23),
new Hourly ("Michael", "678 Fifth Ave.", "555-0690", "958-47-3625", 10.55),
new Volunteer ("Adrianna", "987 Babe Blvd.", "555-8374"),
new Volunteer ("Benny", "321 Dud Lane", "555-7282"),
new Commission("Christopher", "345 Movie Lane", "555-3831", "302-48-3871", 6.25, 0.2),
new Commission("Bobby", "61 Train St.", "555-2869", "492-58-2956", 9.75, 0.15)
};
// ----------------------------------
// Constructor: Updates staff members
// ----------------------------------
public Staff()
{
((Executive)staff_list[0]).awardBonus(500.00);
((Hourly)staff_list[3]).addHours(40);
((Commission)staff_list[6]).addHours(35); // add commissioned employees
((Commission)staff_list[7]).addHours(40);
}
// ----------------------
// Pays all staff members
// ----------------------
public void payday()
{
double amount;
for (int count=0; count < staff_list.length; count++)
{
System.out.println(staff_list[count]);
amount = staff_list[count].pay();
if (amount == 0.0)
System.out.println("Thanks!");
else
System.out.println("Paid: " + fmt.format(amount));
System.out.println("-----------------------------------");
}
}
}
First of all, I don't see your field total_sales being initialized in your Commission constructor.
Also, I am not sure what you mean by first and second employee, if you are referring to staff_list[1] and staff_list[2] they are Employee class so verify that the Employee constructor is being properly initialized, the only way I see them earning any money is if they have some hard-coded number being returned in the Employee.pay() method.
I have a program that calculates an employees annual salary based upon there base salary and commission sales. I want to take the program a step further and create an arrayList that will ask for the employee name and then create an array, store the values from the program and print out those values for each employee name inputted.
I imagine that I need to create a for or a else loop to collect the data. Problem is I'm not sure where to do that and how to create the array. I have two classes:
1 class for my commission variable's and calculations:
package Commissions;
public class Calculations {
double totalSales;
private double comRate = 0.025;
private double annualSal = 80000;
private double salesTarget = 120000;
private double acceleration = 0.015;
private double compensation;
public Calculations (double TotalSales) {
this.totalSales = totalSales;
}
public double getCommissionCalc () {
if (totalSales >= salesTarget) {
compensation = (annualSal + (totalSales * (comRate + acceleration)));
return compensation;
} else if (totalSales >= salesTarget * .8) {
compensation = (annualSal + (totalSales * comRate));
return compensation;
} else {
compensation = annualSal;
return compensation;
}
}
}
1 class for my main and user input
package Commissions;
import java.text.NumberFormat;
import java.util.*;
public class paycheck {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println("Enter the employee name: ");
long empName = input.nextLong();
mediaArray[empName];
System.out.println("Enter your total sales for the year: ");
double totalSales = input.nextDouble();
System.out.println("\r");
Calculations c = new Calculations (totalSales);
System.out.println("Your Total compensation with your annual sales is: " + nf.format(c.getCommissionCalc()));
System.out.println("\r");
System.out.println("If you were to increase your sales you could earn even more money!");
System.out.println("\r");
double i = totalSales + 5000;
double finish = totalSales * 1.5;
while (i <= finish) {
c.totalSales = i;
System.out.println("If you were to increase your sales commission to " + nf.format(i) + " you could earn: " + nf.format(c.getCommissionCalc()));
i = i + 5000;
}
}
}
Here is the code as per my understanding of your problem, had to correct few things as you are saying enter name but taking long as input:
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Paycheck {
public static void main(String[] args) {
List<Employee> empList = new ArrayList<Employee>();
while (true) {
Scanner input = new Scanner(System.in);
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println("Enter the employee name (enter exit to exit): ");
String empName = input.nextLine();
// mediaArray[empName];
if(empName.equals("exit")) {
break;
}
System.out.println("Enter your total sales for the year: ");
double totalSales = input.nextDouble();
Calculations c = new Calculations(totalSales);
System.out
.println("Your Total compensation with your annual sales is: "
+ nf.format(c.getCommissionCalc()));
System.out.println("\r");
System.out
.println("If you were to increase your sales you could earn even more money!");
System.out.println("\r");
double i = totalSales + 5000;
double finish = totalSales * 1.5;
while (i <= finish) {
c.totalSales = i;
System.out
.println("If you were to increase your sales commission to "
+ nf.format(i)
+ " you could earn: "
+ nf.format(c.getCommissionCalc()));
i = i + 5000;
}
System.out.println("\r");
//store employee data into arraylist
empList.add(new Employee(empName, i));
}
for(Employee emp : empList) {
System.out.println("Employee Name: " + emp.getName() + " Total Sales: " + emp.getSales());
}
}
}
class Employee {
private String name;
private Double sales;
public Employee(String empName, double totalSales) {
this.name = empName;
this.sales = totalSales;
}
public Double getSales() {
return sales;
}
public void setSales(Double sales) {
this.sales = sales;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Working on a java program that computes salaries for a collection of employees of different types, which is imported from a TXT file.
The program builds and runs successfully if I comment out:
System.out.println("\nAverage Salary for 2014: " + (totalSalary / indexYear2014));
System.out.println("\nAverage Salary for 2015: " + (totalSalary / indexYear2015));
However, it does not seem that the data is imported/used at all.
Here is the full code:
package computeemployeesalary;
/**
*
* #author Jason Snook
* Course name: Intermediate Programming (CMIS 242)
* Assignment: Project 1 - Compute Employee Salary
*/
/**
* This program computes the salaries of a collection of employees of
* different types: Employee, Salesman, Executive
*
* Salary for employee is calculated by multiplying monthly salary by 12
*
* Salary for salesman takes the base of employee, and then adds commission,
* which has a cap of 20000
*
* Salary for executive takes the base of employee, and then adds a bonus
* in the event that the current stock is more than 100
*/
// Imports
import java.util.Scanner;
import java.io.*;
/**
* This class contains the employee name and monthly salary
*/
// Employee class
class Employee {
// Variable declaration
String employeeName;
int monthlySalary = 0;
// Employee constructor
public Employee(String employeeName, int monthlySalary) {
this.employeeName = employeeName;
this.monthlySalary = monthlySalary;
} // end Employee constructor method
// Calculate employee annual salary
public int annualSalary() {
return monthlySalary * 12;
} // end annualSalary method
// Return employee name and annual salary as String
#Override // takes advantage from compiler checking
public String toString() {
return "Employee Name: " + employeeName +
" Salary: $" + monthlySalary;
} // end toString method
} // end employee class
/**
* This class contains the salesman annual sales and extends employee class
*/
// Salesman subclass, extends Employee class
class Salesman extends Employee {
// Variable declaration
int annualSales = 0;
// Salesman constructor
public Salesman(String employeeName, int monthlySalary, int annualSales) {
super(employeeName, monthlySalary);
this.annualSales = annualSales;
} // end Salesman constructor method
#Override // takes advantage from compiler checking
// Computes commission and annual salary
public int annualSalary() {
int commission = annualSales * 3 / 100;
// if commission is greater than 25000, then set commission to 25000
if (commission > 25000) {
commission = 25000;
} // emd comission if
return (monthlySalary * 12 + commission);
} // end annualSalary method
#Override // takes advantage from compiler checking
// Displays output details as String
public String toString(){
return "Employee Name: " + employeeName +
" Salary: $" + monthlySalary;
} // end toString method
} // end Salesman class
/**
* This class contains the current stock price and extends employee class
*/
// Executive subclass, extends Employee class
class Executive extends Employee {
// Variable declaration
int currentStockPrice = 0;
// Executive constructor
public Executive(String employeeName,
int monthlySalary, int currentStockPrice) {
super(employeeName, monthlySalary);
this.currentStockPrice = currentStockPrice;
} // end Executive constructor method
#Override // takes advantage from compiler checking
// Computes commission and annual salary
public int annualSalary() {
int executiveBonus = 0;
// Adds executive bonus if stock is greater than 100
if(currentStockPrice > 100) {
executiveBonus = 20000;
} // end executiveBonus if
return (monthlySalary * 12 + executiveBonus);
} // end annualSalary method
#Override // takes advantage from compiler checking
// Displays output details as String
public String toString() {
return "Employee Name: " + employeeName +
" Salary: $" + monthlySalary;
} // end toString method
} // end Executive class
/**
* This class computes salary based on input file and reports results
*/
public class ComputeEmployeeSalary {
// Main method
public static void main(String[] args) throws IOException {
// Import text file and compute salary increase
try {
// Create a File instance
java.io.File file = new java.io.File("employees.txt");
// Create Scanner object
Scanner input = new Scanner(file);
// Create arrays for 2014 and 2015
Employee year2014[] = new Employee[20];
Employee year2015[] = new Employee[20];
// Create indexes for 2014 and 2015 arrays
int indexYear2014 = 0, indexYear2015 = 0;
// Read data from a file
while (input.hasNext()) {
String year = input.next();
String employeeTitle = input.next();
String employeeName = input.next();
int monthlySalary = input.nextInt();
// Action if employee is a regular employee.
if (employeeTitle.equalsIgnoreCase("Employee")) {
Employee regularEmployee = new Employee(employeeName,
monthlySalary);
if (year == "2014") {
year2014[indexYear2014++] = regularEmployee;
} // end 2014 if
if (year == "2015") {
year2015[indexYear2015++] = regularEmployee;
} // end 2015 if
} // end Employee if
// Action if employee is a salesman.
if (employeeTitle.equalsIgnoreCase("Salesman")){
int annualSales = input.nextInt();
Salesman salesEmployee = new Salesman(employeeName,
monthlySalary, annualSales);
if (year == "2014") {
year2014[indexYear2014++] = salesEmployee;
} // end 2014 if
if (year == "2015") {
year2015[indexYear2015++] = salesEmployee;
} // end 2015 if
} // end Salesman if
// Action if employee is an executive.
if (employeeTitle.equalsIgnoreCase("Executive")) {
int currentStockPrice = input.nextInt();
Executive executiveEmployee = new Executive(employeeName,
monthlySalary, currentStockPrice);
if (year == "2014") {
year2014[indexYear2014++] = executiveEmployee;
} // end 2014 if
if (year == "2015") {
year2015[indexYear2015++] = executiveEmployee;
} // end 2015 if
} // end Executive if
} // end While
// Generate Report for 2014
int totalSalary = 0;
System.out.println("===== Salary Report for 2014 =====");
for (int i = 0; i < indexYear2014; i++) {
System.out.print(year2014[i]);
System.out.println(" Annual Salary: " +
year2014[i].annualSalary());
} // end annualSalary 2014 for
for (int i = 0; i < indexYear2014; i++) {
totalSalary+= year2014[i].annualSalary();
} // end totalSalary 2014 for
System.out.println("\nAverage Salary for 2014: " +
(totalSalary / indexYear2014));
// Generate Report for 2015
System.out.println("\n===== Salary Report for 2015 =====");
for (int i = 0; i < indexYear2015; i++) {
System.out.print(year2015[i]);
System.out.println(" Annual Salary: " +
year2015[i].annualSalary());
} // end annualSalary 2015 for
for (int i = 0; i < indexYear2015; i++) {
totalSalary+= year2015[i].annualSalary();
} // end totalSalary 2015 for
System.out.println("\nAverage Salary for 2015: " +
(totalSalary / indexYear2015));
// Close input file
input.close();
} // end try
catch (IOException i) {
System.out.println("Error: File Not Found, error code: " + i);
} // end catch
} // end main method
} // end ComputeEmployeeSalary class
Any help would be greatly appreciated.
The reason it works when you comment out those 2 lines is that they cause a divide by zero error. Both indexYear2014 and indexYear2015 are 0.
The reason for this is the way you're comparing Strings:
year == "2015" should be year.equals("2015")
For some reason when I input values for RTH and CTH I receive 0.0 values. I had a similar issue on my shift getters, but I managed to fix that. Unfortunately, attempting to reverse engineer the problem hasn't helped. I've provided the code for my class and my driver, although I am almost convinced the issue is somewhere in the class. Nevertheless, can anyone take a quick look at the RTH / CTH setters/ getters and see what I've done wrong in setting or calling them.
public class TeamLeader extends ProductionWorker
{
//private variables
private double RTH;
private double CTH;
private double payRate;
private double monthlyBonus;
//constructor
public TeamLeader(String name, String number, String hd, int shift,
double rate, double monthlyBonus, double RTH, double CTH)
{
super(name, number, hd, shift, rate);
this.monthlyBonus = monthlyBonus;
}
public void setmonthlyBonus(double monthlyBonus)
{
this.monthlyBonus = monthlyBonus;
}
public void setpayRate(double payRate)
{
this.payRate = payRate;
}
public void setRTH(double r)
{
RTH = r;
}
public void setCTH(double c)
{
CTH = c;
}
//Getters
public double getmonthlyBonus()
{
return monthlyBonus;
}
public double getpayRate()
{
return payRate;
}
public double getRTH()
{
return RTH;
}
public double getCTH()
{
return CTH;
}
}
Driver
public class WorkDriver {
public static void main(String[] args) {
String name;
String number;
String hireDate;
int shift;
double payRate;
double monthlyBonus;
double RTH;
double CTH;
name = JOptionPane.showInputDialog("Enter your name");
number = JOptionPane.showInputDialog
("Enter your number (Format: XXX-L)");
hireDate = JOptionPane.showInputDialog("Enter your hire date");
shift = Integer.parseInt(JOptionPane.showInputDialog
("Please enter the work shift for the employee:\n"
+ "\tEnter 1 for the day shift"
+ "\n\tEnter 2 for the night shift"));
payRate = Double.parseDouble(JOptionPane.showInputDialog
("Enter your pay rate"));
monthlyBonus = Double.parseDouble(JOptionPane.showInputDialog
("Enter your monthly bonus"));
RTH = Double.parseDouble(JOptionPane.showInputDialog
("Enter your required traing hours"));
CTH = Double.parseDouble(JOptionPane.showInputDialog
("Enter your training hours attended"));
//Production worker object
TeamLeader driver = new TeamLeader(name, number,
hireDate, shift, payRate, monthlyBonus, RTH, CTH);
JOptionPane.showMessageDialog(null,
"----------- Employe Info ----------------"
+ "\nName: " + driver.getName()
+ "\nEmployee Number: " + driver.getNumber()
+ "\nHire Date: " + driver.getHireDate()
+ "\nPay Rate: " + driver.getPayRate()
+ "\nShift: " + driver.getShift()
+ "\nMonthly Bonus: " + driver.getmonthlyBonus()
+ "\nRequired Training Hours: " + driver.getRTH()
+ "\nTraining Hours Attended: " + driver.getCTH());
System.exit(0);
}
}
You never call the setters of CTH and RTH. You pass their values to your constructor but don't use them.
Add to your constructor setting of CTH and RTH :
public TeamLeader(String name, String number, String hd, int shift,
double rate, double monthlyBonus, double RTH, double CTH)
{
super(name, number, hd, shift, rate);
this.monthlyBonus = monthlyBonus;
this.RTH = RTH;
this.CTH = CTH;
}
You're calling the parent (super) constructor, but it doesn't take RTH or CTH, and you never set RTH and CTH on your TeamLeader object.
public TeamLeader(String name, String number, String hd, int shift,
double rate, double monthlyBonus, double RTH, double CTH)
{
super(name, number, hd, shift, rate);
this.monthlyBonus = monthlyBonus;
this.RTH = RTH;
this.CTH = CTH;
}
You are not setting the passed RTH to the instance's RTH. See code above for the fix