Import data in file and use to compute salary [closed] - java

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")

Related

scanner nextLine() skip and failed read

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

Outputting information using super and overwriting

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.

Getting java.lang.NumberFormatException When Outputting

I am using BlueJ, for reference.
The program compiles fine. It runs fine as well except that this:
java.lang.NumberFormatException: For input string: "Washington,George"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at WorkerApp.main(WorkerApp.java:53)
at __SHELL112.run(__SHELL112.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at bluej.runtime.ExecServer$3.run(ExecServer.java:730)
Specifically highlighting:
java.lang.NumberFormatException: For input string: "Washington,George"
at WorkerApp.main(WorkerApp.java:53)
The point of this program is to read a text file and add to said text file.
The program is supposed to read and open "EmployeeData.txt":
S Washington,George 000001 125000
H MacDonald,Ronald 386218 7.80 true 40
H Walton,Samuel 268517 8.21 false
H Thomas,David 131313 9.45 true 38
H Sanders,HarlandDavid 277651 8.72 false
S Baron,James 368535 310236
When I click on the exception it highlights this from my main class
double salary = Double.parseDouble(Employee[3]);
This is the full main class WorkerApp in which I am trying to read and open the text file:
import java.io.*;
import java.util.*;
public class WorkerApp{
/**
* Reads the infile, runs tests, and prints the output.
*/
public static void main (String args[]){
Company company = new Company();
try{
Scanner reader = new Scanner (new File("EmployeeData.txt"));
while(reader.hasNext()){
String line = reader.nextLine();
String Employee[] = line.split(" ");
String sorh = Employee[0];
String name = Employee[1];
String id = Employee[2];
double salary = Double.parseDouble(Employee[3]);
Employee e;
if (Employee[0].equals("S")){
e = new SalariedWorker(sorh, name, id, salary);}
else {
boolean overtime = Boolean.parseBoolean(Employee[4]);
if(overtime){
int maxHours = Integer.parseInt(Employee[5]);
e = new HourlyWorker(sorh, name, id, salary, maxHours);
}
else{
e = new HourlyWorker(sorh, name, id, salary);
}
}
company.add(e);
}
}catch (Exception err){
//System.out.println(err);
err.printStackTrace();
}
company.print();
System.out.println();
//Test Number 1
System.out.println("1) Add a salaried worker");
SalariedWorker SWorker1 = new SalariedWorker("S", "Moran,Blake", "123456", 260000);
company.add(SWorker1);
company.print();
//Test Number 2
System.out.println("2) Add an hourly worker who has no overtime allowed");
HourlyWorker HWorker1 = new HourlyWorker("H", "Bob,Billy", "654321", 15);
company.add(HWorker1);
company.print();
//Test Number 3
System.out.println("3) Add an hourly worker who has overtime allowed");
HourlyWorker HWorker2 = new HourlyWorker("H", "Smith,Will", "345612", 10.5, 30);
company.add(HWorker2);
company.print();
//Test Number 4
System.out.println("4) Add a worker that is already in the database");
try{
company.add(SWorker1);
}catch(Exception err){
System.out.println(err);
System.out.println();
}
//Test Number 5
System.out.println("5) Print the sorted list");
company.print();
//Test Number 6
System.out.println("6) Remove a worker who is NOT in the list");
company.remove("Brooks,Phil");
System.out.println();
//Test Number 7
System.out.println("7) Remove a worker who is the first in the list ");
company.remove("Moran,Blake");
company.print();
System.out.println();
//Test Number 8
System.out.println("8) Find a worker who is the middle of the list");
int index = company.find("Bob,Billy");
System.out.println("Found at "+ index);
System.out.println();
//Test Number 9
System.out.println("9) Find a worker who is NOT in the list");
index = company.find("Harrison,Ford");
System.out.println("Found at "+ index);
System.out.println();
//Test Number 10
System.out.println("10) Find the weekly salary of a worker who is salaried");
System.out.println(SWorker1.FindSalary());
System.out.println();
//Test Number 11
System.out.println("11) Find the weekly salary of an hourly worker who has no overtime allowed [50 hours]");
System.out.println(HWorker1.FindSalary(50));
System.out.println();
//Test Number 12
System.out.println("12) Find the weekly salary of an hourly worker who has overtime allowed [50 hours]");
System.out.println(HWorker2.FindSalary(50));
System.out.println();
//Test Number 13
System.out.println("13) Find the weekly salary of an hourly worker who has overtime allowed [20 hours]");
System.out.println(HWorker2.FindSalary(20));
System.out.println();
//Test Number 14
System.out.println("14) Print the sorted list");
company.print();
//Test Number 15
System.out.println("\n15) End the process");
}
}
It should be noted that on top of the exception it spits out this output:
1) Add a salaried worker
S Moran,Blake 123456 260000.0
2) Add an hourly worker who has no overtime allowed
S Moran,Blake 123456 260000.0
H Bob,Billy 654321 15.0 false
3) Add an hourly worker who has overtime allowed
S Moran,Blake 123456 260000.0
H Bob,Billy 654321 15.0 false
H Smith,Will 345612 10.5 true 30
4) Add a worker that is already in the database
java.lang.RuntimeException: The Employee Is Not New
5) Print the sorted list
S Moran,Blake 123456 260000.0
H Bob,Billy 654321 15.0 false
H Smith,Will 345612 10.5 true 30
6) Remove a worker who is NOT in the list
The Employee is not Found
7) Remove a worker who is the first in the list
H Bob,Billy 654321 15.0 false
H Smith,Will 345612 10.5 true 30
8) Find a worker who is the middle of the list
Found at 0
9) Find a worker who is NOT in the list
Found at -1
10) Find the weekly salary of a worker who is salaried
5000.0
11) Find the weekly salary of an hourly worker who has no overtime allowed [50 hours]
750.0
12) Find the weekly salary of an hourly worker who has overtime allowed [50 hours]
630.0
13) Find the weekly salary of an hourly worker who has overtime allowed [20 hours]
210.0
14) Print the sorted list
H Bob,Billy 654321 15.0 false
H Smith,Will 345612 10.5 true 30
15) End the process
If it helps, here are my other classes for reference, as they might be the source of the problem.
Company:
import java.io.*;
import java.util.*;
public class Company{
private Employee[] employeeArray;
private final int InitialCapacity = 7;
private int employCount;
/**
* Creates the employee array and sets employCount to 0.
*/
public Company(){
employeeArray = new Employee[InitialCapacity];
employCount = 0;
}
/**
* Finds an employee in the list.
*/
public int find(String name){
for (int i = 0; i < employCount; i++){
if (employeeArray[i].getName().equals(name)){
return i;
}
}
return -1;
}
/**
* Adds an employee to the list.
*/
public int add(Employee employ){
int index;
for (index = 0; index < employCount; index++){
int result = employeeArray[index].getName().compareTo(employ.getName());
if(result == 0){
throw new RuntimeException ("The Employee Is Not New");
}
}
if (employeeArray.length == employCount){
expand();
}
employeeArray[index] = employ;
employCount++;
return index;
}
/**
* Removes an employee to the list.
*/
public void remove(String name){
int index = find(name);
if (index == -1){
System.out.println("The Employee is not Found");
return;
}
for (int i = index; i < employCount - 1; i++){
employeeArray[i] = employeeArray[i + 1];
}
employCount--;
}
/**
* Prints the list.
*/
public void print(){
if(employCount == 0){
System.out.println("The List is Empty");
return;
}
for(int i = 0; i < employCount; i++){
System.out.println(employeeArray[i]);
}
}
/**
* Expands the list.
*/
private void expand(){
Employee[] newArray = new Employee[employeeArray.length + InitialCapacity];
for (int i = 0; i < employeeArray.length; i++){
newArray[i] = employeeArray[i];
}
employeeArray = newArray;
}
}
Employee:
import java.io.*;
import java.util.*;
public class Employee{
private String SorH;
private String name;
private String ID;
/**
* Sets sets SorH, name, and ID to SH, n, and id.
*/
public Employee (String SH, String n, String id){
SorH = SH;
name = n;
ID = id;
}
/**
* Gets the first part (S or H) of the employee list.
*/
public String getSorH(){
return SorH;
}
/**
* Gets the name of the employee list.
*/
public String getName(){
return name;
}
/**
* Gets the ID of the employee list.
*/
public String getID(){
return ID;
}
/**
* Sets SorH to SH.
*/
public void setSorH(String SH){
SorH = SH;
}
/**
* Sets name to n.
*/
public void setName(String n){
name = n;
}
/**
* Sets ID to id.
*/
public void setID(String id){
ID = id;
}
/**
* Returns a string representing the employee list.
*/
public String toString(){
return String.format("%s %s %s", getSorH(), getName(), getID());
}
}
HourlyWorker:
import java.io.*;
import java.util.*;
public class HourlyWorker extends Employee{
private double hourlySalary;
private boolean overtime;
private int maxHours;
/**
* Contains the super and sets the hourly salary and maxHours to hourlySal and maxH and
* overtime to true.
*/
public HourlyWorker(String SH, String n, String id, double hourlySal, int maxH){
super(SH, n, id);
hourlySalary = hourlySal;
overtime = true;
maxHours = maxH;
}
/**
* Contains the super and sets the hourly salary to hourlySal and overtime to false.
*/
public HourlyWorker(String SH, String n, String id, double hourlySal){
super(SH, n, id);
hourlySalary = hourlySal;
overtime = false;
}
/**
* Returns if overtime is true or false.
*/
public boolean overtime(){
return overtime;
}
/**
* Gets the max hours of an hourly worker.
*/
public int getmaxH(){
return maxHours;
}
/**
* Gets the hourly salary of an hourly worker.
*/
public double gethourlySalary(){
return hourlySalary;
}
/**
* Sets hourly salary to hSalary.
*/
public void sethourlySalary (double hSalary){
hourlySalary = hSalary;
}
/**
* Finds the weekly salary of an hourly worker.
*/
public double FindSalary(double hoursWorked){
if (overtime){
if (hoursWorked <= maxHours){
return hoursWorked * hourlySalary;
} else{
return maxHours * hourlySalary +
(hoursWorked - maxHours) * hourlySalary * 1.5;
}
} else{
return hoursWorked * hourlySalary;
}
}
/**
* Contains the super string and adds onto the string.
*/
public String toString(){
String str = super.toString() + String.format(" %s %s", gethourlySalary(),overtime());
if (overtime){
str = str + String.format(" %s", getmaxH());
}
return str;
}
}
SalariedWorker:
import java.io.*;
import java.util.*;
public class SalariedWorker extends Employee{
private double yearlySalary;
/**
* Contains the super and sets yearly salary to ySalary.
*/
public SalariedWorker(String SH, String n, String id, double ySalary){
super(SH, n, id);
yearlySalary = ySalary;
}
/**
* Gets the yearly salary of a salaried worker.
*/
public double getyearlySalary(){
return yearlySalary;
}
/**
* Sets the yearly salary of a salaried worker.
*/
public void setyearlySalary(double ySalary){
yearlySalary = ySalary;
}
/**
* Finds the weekly salary of a salaried worker.
*/
public double FindSalary(){
return yearlySalary / 52;
}
/**
* Contains the super string and adds onto the string.
*/
public String toString(){
return super.toString() + String.format(" %s", getyearlySalary());
}
}
Thank you in advance!
Instead of line.split(" "); you might want to try line.split("\\s+"). I think the splitting is not happening properly.
Don't you have access to a debugger ? There should be one in any IDE you can use, be it Netbeans, Eclipse, IntelliJ or ...
Just put a breakpoint on the line where exception occurs and look at the values in the Employee array. The cause of the error should then be self evident.
In case it is still not evident for you, here is next clue : read again the javadoc for String.split() and compare with what you have in Employee.

method not printing all values in java

i have 2 java programs , the first one takes all information about the employee(id , name , department etc)from the user and prints it , the second program lets the user choose how many number of employees are there then it takes the values like(employ id, name etc), this program uses an array to store the values , it should print all values of different employees , but when i run the program the second set of values overrides the first set of values and prints the second set of values twice , im a beginner so plse help
This is the first program
import java.util.Scanner;
public class payroll2
{
public static void main(String args[])
{
payroll2 payroll = new payroll2();
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
payroll.GetPayroll();
}
Scanner myScanner=new Scanner(System.in);
int empID;
String empName;
String empDept;
String designation;
int basicSalary;
double bonus;
double commission;
double nssf;
double netSalary;
public void SetPayrollDetail()
{
System.out.println("Enter ID: ");
empID = myScanner.nextInt();
System.out.println("Enter Name: ");
empName = myScanner.next();
System.out.println("Enter Department (Marketing or Other): ");
empDept = myScanner.next();
System.out.println("Enter Designation (Manager, Executive or Other): ");
designation = myScanner.next();
System.out.println("Enter Basic Salary: ");
basicSalary = myScanner.nextInt();
}
public void SetBonus()
{
if(basicSalary < 1500){
bonus = 0.0;
}
else if(basicSalary>=1500 && basicSalary<3000){
bonus = basicSalary * (12.0/100.0);
}
else if(basicSalary>=3000 && basicSalary<5000){
bonus = basicSalary * (15.0/100.0);
}
else{
bonus = basicSalary * (25.0/100.0);
}
}
public void SetCommission()
{
if( empDept.equalsIgnoreCase("other") ){
commission = 0.0;
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("manager") ){
commission = basicSalary * (30.0/100.0);
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("executive") ){
commission = basicSalary * (15.0/100.0);
}
else if( empDept.equalsIgnoreCase("marketing") && designation.equalsIgnoreCase("other") ){
commission = basicSalary * (10.0/100.0);
}
else{
commission = 0.0;
}
}
public void SetNssf()
{
if(basicSalary < 1500){
nssf = basicSalary * (5.0/100.0);
}
else if(basicSalary>=1500 && basicSalary<3000){
nssf = basicSalary * (8.0/100.0);
}
else if(basicSalary>=3000 && basicSalary<5000){
nssf = basicSalary * (12.0/100.0);
}
else if(basicSalary>=5000 && basicSalary<7000){
nssf = basicSalary * (15.0/100.0);
}
else if(basicSalary>=7000 && basicSalary<10000){
nssf = basicSalary * (20.0/100.0);
}
else{
nssf = basicSalary * (25.0/100.0);
}
}
public void SetNetSalary()
{
netSalary = ( basicSalary + commission + bonus ) - nssf;
}
public void GetPayroll()
{
System.out.println("\n\nPayroll Details \n _____________________");
System.out.println("ID:\t\t" + empID);
System.out.println("name:\t\t" + empName);
System.out.println("Bonus:\t\t" + bonus);
System.out.println("Commission:\t"+commission);
System.out.println("NSSF:\t\t"+nssf);
System.out.println("Net Salary:\t"+netSalary);
}
}
This is the second program
import java.util.Scanner;
public class display{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
int counter;
int limit;
System.out.println("How many employess do u want to enter?\n Enter here: ");
limit = scan.nextInt();
int[] a = new int[limit];
payroll2 payroll = new payroll2();
for(counter=1; counter<=limit; counter++){
System.out.println("\n\nEnter employee "+counter+" details\n");
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
}
for(counter=1; counter<=limit; counter++){
payroll.GetPayroll();
//System.out.println(a);
}
}
}
This is the area of code that there's a problem in:
for(counter=1; counter<=limit; counter++){
System.out.println("\n\nEnter employee "+counter+" details\n");
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
}
for(counter=1; counter<=limit; counter++){
payroll.GetPayroll();
//System.out.println(a);
}
If you think about what this does. So a payroll2 object is a single entity. When you enter them in the first for loop, you create one person. Then if you loop through that a second or third time, you overwrite that person, since you are saving to the same variable.
Then when you loop through the second loop, you are printing the payroll entity, which holds the value of the last entered person. Since the other data gets overwritten, its no surprise that you get the same guy printed limit times.
What you will want to do is build an array of payroll entities. This code accomplishes this:
payroll2[] PayrollList = new payroll2[limit]; // establish the array with correct size
for(counter=0; counter<=limit - 1; counter++){ // bounds of the array are 0 to limit - 1
payroll = new payroll(); // hard reset of the variable to make sure data is cleared
System.out.println("\n\nEnter employee "+counter+" details\n");
payroll.SetPayrollDetail();
payroll.SetBonus();
payroll.SetCommission();
payroll.SetNssf();
payroll.SetNetSalary();
PayrollList[counter] = payroll; // adds it to the array at position counter
}
for(counter=0; counter<=limit - 1; counter++){
PayrollList[counter].GetPayroll(); // gets the payroll2 object from the array and calls its function
}
DISCLAIMER: I have not run the modified code through a compiler, so it may not be 100% syntax correct, but it is very close.

How to get the calculation results to print - Java

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();
}
}
}

Categories

Resources