Question

HOW TO FiX EXCEPTIONS??? In order to populate the array, you will need to split() each...

HOW TO FiX EXCEPTIONS???

In order to populate the array, you will need to split() each String on the (,) character so you can access each individual value of data. Based on the first value (e.g., #) your method will know whether to create a new Manager, HourlyWorker, or CommissionWorker object. Once created, populate the object with the remaining values then store it in the array. Finally, iterate through the array of employees using the enhanced for loop syntax, and print out each employee in the following format:

Manager:

    Steve Davis     $2000

Commission Employee:

   John Kanet      $1500 (Base salary: $800, sales: $7000, Commission rate: 10%)

Hourly Worker:

Thomas Hill    $1100 (Hourly wage: $20, hours worked: 50)

 

this is what the text file says:

#Steve, Davis, 2000
*John, Kanet, 800, 7000, 0.10
@Thomas, Hill,20,50
*Lisa, Green,800,6000,0.10
*Chasidy , Funderburk,1000,5000,0.08
@Kayleigh , Bertrand, 25, 45
*Zane, Eckhoff,1800,900, 0.09
@Teressa, Bitterman, 15,35
*Yuri, Viera, 600, 5000,0.10

these are the files i needed to work on and have completed:

public class HourlyWorker extends Employee {

private double hoursWorked;
private int wage;

  
public HourlyWorker(String firstName, String lastName, double hoursWorked,
int wage) {
super(firstName, lastName);
this.hoursWorked = hoursWorked;
this.wage = wage;
}


public double getHoursWorked() {
return hoursWorked;
}

  
public int getWage() {
return wage;
}

  
public void setHoursWorked(double hoursWorked) {
this.hoursWorked = hoursWorked;
}


public void setWage(int wage) {
this.wage = wage;
}


public double earnings() {
// TODO Auto-generated method stub
double pay;
if (hoursWorked > 40) {
pay = (40 * wage) + (1.5 * (hoursWorked - 40) * wage);

} else {

pay = wage * hoursWorked;
}
return pay;
}

}

_________________________________________________________________

public class Manager extends Employee {

private double weeklySalary;


public Manager(String firstName, String lastName, double weeklySalary) {
super(firstName, lastName);
this.weeklySalary = weeklySalary;
}

  
public double getWeeklySalary() {
return weeklySalary;
}


public void setWeeklySalary(double weeklySalary) {
this.weeklySalary = weeklySalary;
}

  
public double earnings() {
// TODO Auto-generated method stub

return getWeeklySalary();
}

}

_________________________________________________________________

public class CommissionEmployee extends Employee {

double weeklySalary, commissionRate, weeklySales;

  
public CommissionEmployee(String firstName, String lastName,
double weeklySalary, double commissionRate, double weeklySales) {
super(firstName, lastName);
this.weeklySalary = weeklySalary;
this.commissionRate = commissionRate;
this.weeklySales = weeklySales;
}

  
public double getWeeklySalary() {
return weeklySalary;
}

  
public double getCommissionRate() {
return commissionRate;
}


public double getWeeklySales() {
return weeklySales;
}


public void setWeeklySalary(double weeklySalary) {
this.weeklySalary = weeklySalary;
}

  
public void setCommissionRate(double commissionRate) {
this.commissionRate = commissionRate;
}


public void setWeeklySales(double weeklySales) {
this.weeklySales = weeklySales;
}

public double earnings() {
return weeklySalary + (commissionRate * weeklySales);
}

}


_________________________________________________________________

import java.io.File;
import java.util.Scanner;

public class Payroll2 {

public static void main(String[] args) {

Scanner scanner = null;
try {
Scanner input = new Scanner(new File(args[0]));

Employee[] employees;
int n = 0;
if (input.hasNext())
n = Integer.parseInt(input.nextLine());
employees = new Employee[n];
char empType;
int i = 0;
while (scanner.hasNext()) {

String line = scanner.nextLine();

empType = line.charAt(0);
System.out.println(line);
String lineArr[] = line.split(",");
String firstName = lineArr[0].substring(1);
String lastName = lineArr[1];
switch (empType) {
case '#': {
double weeklySalary = Double.parseDouble(lineArr[2].trim());
Manager managers = new Manager(firstName, lastName,
weeklySalary);
employees[i] = managers;

}
break;
case '@': {
int wage = Integer.parseInt(lineArr[2].trim());
int hoursWorked = Integer.parseInt(lineArr[3].trim());
HourlyWorker hourlyWorker = new HourlyWorker(firstName,
lastName, hoursWorked, wage);
employees[i] = hourlyWorker;

}

break;
case '*': {

double weeklySalary = Double.parseDouble(lineArr[2].trim());
double weeklySales = Double.parseDouble(lineArr[3].trim());
double commissionRate = Double.parseDouble(lineArr[4]
.trim());

CommissionEmployee commissionEmployee = new CommissionEmployee(
firstName, lastName, weeklySalary, commissionRate,
weeklySales);
employees[i] = commissionEmployee;
}

break;
default:
break;
}
i++;

}
for (int j = 0; j < employees.length; j++) {
System.out.println(employees[j].getClass() + ": "
+ employees[j]);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}

_____________________________________________________________________

these are the errors im getting:

java.lang.NumberFormatException: For input string: "#Steve, Davis, 2000"
   at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
   at java.lang.Integer.parseInt(Integer.java:569)
   at java.lang.Integer.parseInt(Integer.java:615)
   at Payroll2.main(Payroll2.java:15)

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

Hi, there is an exception because you are trying to parse from the very first line which is a string,

i guess you are assuming there will number of employees present in the file, if its present then your code will work and i have made few changes to meet other requirements, commented the code to help you understand.

Also, if you dont want to take the original assumption that number of employees is not given, then use an arraylist, i have also mentioned that in comments in the program.

Feel free to ask any questions you have in comments.

import java.io.File;

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

public class Payroll {

public static void main(String[] args) {

Scanner scanner = null;

try {

Scanner input = new Scanner(new File(args[0]));

  

Employee[] employees;

int n = 0;

if (input.hasNext())

n = Integer.parseInt(input.nextLine()); // this will fetch the very first line, so it should be an integer i.e. no of employees

employees = new Employee[n];

/* if you dont want to give number in the file, consider using array list like below*/

//List<Employee> newemployees= new ArrayList<>();

//replace employees[i]= managers with newemployees.add(managers)

// if you are using arraylist you can do away with the above code of initializing array with n

char empType;

int i = 0;

while (scanner.hasNext()) {

String line = scanner.nextLine();

empType = line.charAt(0);

System.out.println(line);

String lineArr[] = line.split(",");

// String firstName = lineArr[0].substring(1);// this will remove the first letter of last name, you should remove the substring part

String firstName = lineArr[0];

String lastName = lineArr[1];

switch (empType) {

case '#': {

double weeklySalary = Double.parseDouble(lineArr[2].trim());

Manager managers = new Manager(firstName, lastName,

weeklySalary);

employees[i] = managers;

}

break;

case '@': {

int wage = Integer.parseInt(lineArr[2].trim());

int hoursWorked = Integer.parseInt(lineArr[3].trim());

HourlyWorker hourlyWorker = new HourlyWorker(firstName,

lastName, hoursWorked, wage);

employees[i] = hourlyWorker;

}

break;

case '*': {

double weeklySalary = Double.parseDouble(lineArr[2].trim());

double weeklySales = Double.parseDouble(lineArr[3].trim());

double commissionRate = Double.parseDouble(lineArr[4]

.trim());

CommissionEmployee commissionEmployee = new CommissionEmployee(

firstName, lastName, weeklySalary, commissionRate,

weeklySales);

employees[i] = commissionEmployee;

}

break;

default:

break;

}

i++;

}

// for (int j = 0; j < employees.length; j++) {

// System.out.println(employees[j].getClass() + ": "

// + employees[j]);

// }

for (Employee j: employees) { // enhanced for loop

if(j instanceof Manager) // checking if he is a manager

{

System.out.println("Manager:");

System.out.println(j.getfirstName()+ " "+j.getlastName()+" $"+((Manager)j).getWeeklySalary() );

}

else if(j instanceof CommissionEmployee)// checking if he is a CommissionEmployee

{

System.out.println("CommissionEmployee:");

System.out.println(j.getfirstName()+ " "+j.getlastName()+" $(Base salary:"

+((CommissionEmployee)j).weeklySalary+",sales: $"+((CommissionEmployee)j).weeklySales+",Commission rate: "+((CommissionEmployee)j).commissionRate+"%)");

}

else

{

System.out.println("Hourly Worker:");

double wage = ((HourlyWorker)j).getWage();

int hours = ((HourlyWorker)j).getHoursWorked();

int earnings = ((HourlyWorker)j).earnings();

System.out.println(j.getfirstName()+ " "+j.getlastName()+" $"+earnings+"(Hourly wage: $"+wage+",hours worked: "+hours+")" );

}

  

  

}

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}

}

}

----------------

package practice;

public class Manager extends Employee {

private double weeklySalary;

public Manager(String firstName, String lastName, double weeklySalary) {

super(firstName, lastName);

this.weeklySalary = weeklySalary;

}

public double getWeeklySalary() {

return weeklySalary;

}

public void setWeeklySalary(double weeklySalary) {

this.weeklySalary = weeklySalary;

}

public double earnings() {

// TODO Auto-generated method stub

return getWeeklySalary();

}

}

-----------------------

package practice;

public class CommissionEmployee extends Employee {

double weeklySalary, commissionRate, weeklySales;

public CommissionEmployee(String firstName, String lastName,

double weeklySalary, double commissionRate, double weeklySales) {

super(firstName, lastName);

this.weeklySalary = weeklySalary;

this.commissionRate = commissionRate;

this.weeklySales = weeklySales;

}

public double getWeeklySalary() {

return weeklySalary;

}

public double getCommissionRate() {

return commissionRate;

}

public double getWeeklySales() {

return weeklySales;

}

public void setWeeklySalary(double weeklySalary) {

this.weeklySalary = weeklySalary;

}

public void setCommissionRate(double commissionRate) {

this.commissionRate = commissionRate;

}

  

public void setWeeklySales(double weeklySales) {

this.weeklySales = weeklySales;

}

public double earnings() {

return weeklySalary + (commissionRate * weeklySales);

}

}

--------------

package practice;

public class HourlyWorker extends Employee {

private int hoursWorked;

private double wage;

public HourlyWorker(String firstName, String lastName, int hoursWorked,

double wage) {

super(firstName, lastName);

this.hoursWorked = hoursWorked;

this.wage = wage;

}

  

public int getHoursWorked() {

return hoursWorked;

}

public double getWage() {

return wage;

}

public void setHoursWorked(int hoursWorked) {

this.hoursWorked = hoursWorked;

}

public void setWage(int wage) {

this.wage = wage;

}

public double earnings() {

// TODO Auto-generated method stub

double pay;

if (hoursWorked > 40) {

pay = (40 * wage) + (1.5 * (hoursWorked - 40) * wage);

} else {

pay = wage * hoursWorked;

}

return pay;

}

}

Thumbs up if this was helpful, otherwise let me know in comments

Add a comment
Know the answer?
Add Answer to:
HOW TO FiX EXCEPTIONS??? In order to populate the array, you will need to split() each...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need help in getting the second output to show both the commission rate and the...

    I need help in getting the second output to show both the commission rate and the earnings for the String method output package CompemsationTypes; public class BasePlusCommissionEmployee extends CommissionEmployee { public void setGrossSales(double grossSales) { super.setGrossSales(grossSales); } public double getGrossSales() { return super.getGrossSales(); } public void setCommissionRate(double commissionRate) { super.setCommissionRate(commissionRate); } public double getCommissionRate() { return super.getCommissionRate(); } public String getFirstName() { return super.getFirstName(); } public String getLastName() { return super.getLastName(); } public String getSocialSecurityNumber() { return super.getSocialSecurityNumber(); } private...

  • Add an HourlyPlusCommissionEmployee class to the PayrollSystem app by subclassing an existing class. A HourlyPlusCommissionEmployee is...

    Add an HourlyPlusCommissionEmployee class to the PayrollSystem app by subclassing an existing class. A HourlyPlusCommissionEmployee is a kind of CommissionEmployee with the following differences and specifications: HourlyPlusCommissionEmployee earns money based on 2 separate calculations: commissions are calculated by the CommissionEmployee base class hourly pay is calculated exactly the same as the HourlyEmployee class, but this is not inherited, it must be duplicated in the added class BasePlusCommissionEmployee inherits from CommissionEmployee and includes (duplicates) the details of SalariedEmployee. Use this as...

  • (Reading & Writing Business Objects) I need to have my Classes be able to talk to...

    (Reading & Writing Business Objects) I need to have my Classes be able to talk to Files. How do I make it such that I can look in a File for an account number and I am able to pull up all the details? The file should be delimited by colons (":"). The Code for testing 'Select' that goes in main is: Account a1 = new Account(); a1.select(“90001”); a1.display(); Below is what it should look like for accounts 90000:3003:SAV:8855.90 &...

  • By editing the code below to include composition, enums, toString; must do the following: Prompt the...

    By editing the code below to include composition, enums, toString; must do the following: Prompt the user to enter their birth date and hire date (see Fig. 8.7, 8.8 and 8.9 examples) in addition to the previous user input Create a new class that validates the dates that are input (can copy date class from the book) Incorporate composition into your class with these dates Use enums to identify the employee status as fulltime (40 or more hours worked for...

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

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

  • In Java: Executable Class create an array of Employee objects. You can copy the array you...

    In Java: Executable Class create an array of Employee objects. You can copy the array you made for Chapter 20. create an ArrayList of Employee objects from that array. use an enhanced for loop to print all employees as shown in the sample output. create a TreeMap that uses Strings for keys and Employees as values. this TreeMap should map Employee ID numbers to their associated Employees. process the ArrayList to add elements to this map. print all employees in...

  • FOR JAVA: Summary: Create a program that adds students to the class list (see below). The...

    FOR JAVA: Summary: Create a program that adds students to the class list (see below). The solution should be named Roster402_v2.java. Allow the user to control the number of students added to the roster. Ask if the user would like to see their new roster to confirm additions. If yes, then display contents of the file, if no, end the program. ------------------------------------------------------------------------------------- List of student names and IDs for class (this will be your separate text file): Jones, Jim,45 Hicks,...

  • In the processLineOfData, write the code to handle case "H" of the switch statement such that:...

    In the processLineOfData, write the code to handle case "H" of the switch statement such that: An HourlyEmployee object is created using the firstName, lastName, rate, and hours local variables. Notice that rate and hours need to be converted from String to double. You may use parseDouble method of the Double class as follows:               Double.parseDouble(rate) Call the parsePaychecks method in this class passing the HourlyEmployee object created in the previous step and the checks variable. Call the findDepartment method...

  • I'm attempting to convert ch object array to double array public void calculateSalesPrice() { double salePrice[]...

    I'm attempting to convert ch object array to double array public void calculateSalesPrice() { double salePrice[] = new double[ch.length]; int p = 0; for (int i = 0; i < ch.length; i += 3) { p = i + 1; for(int j = 0;j } } error message:items.java:16: error: cannot find symbol for(int j = 0;j ^ symbol: variable length location: class Object items.java:17: error: array required, but Object found salePrice[j] = (double full program import java.io.File; import java.util.Scanner; import...

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