I have a method in class Employee
called calculatePay
that does calculations for certain pay and taxes.
public void calculatePay() {
totalHoursWorked = 0;
grossPay = 0;
fedTax = 0;
stateTax = 0;
netPay = 0;
totalTax = 0;
for (int i = 0; i < getNoTimeCards(); i++) {
TimeCard timeCard = getTimeCard(i);
totalHoursWorked += timeCard.getHoursWorked();
}
grossPay = totalHoursWorked * payRate;
if (grossPay >= 200) {
fedTax = (grossPay - 200) * .1;
} else {
fedTax = 0;
}
stateTax = grossPay * .04;
totalTax = fedTax + stateTax;
netPay = grossPay - totalTax;
}
I need to create a method called calculatePay
in another class called Company
. In this method, I need to create a loop that calls on the calculatePay
method in Employee
. Is calling on a method in a loop any different than calling on an instance variable? Whatever I try doesn't seem to work. Here's what i
currently have for the method in Company
:
public void calculatePay() {
for (int i = 0; i < noEmployees; i++) {
Employee employee = getEmployee(i);
employee.calculatePay(); {
return;
}
}
}
Any help in explaining would be great.
Ah, I think I see what you tried to do.
So you tried creating a function, then tried to make it return it's calculated value by using the parentheses when calling it, didn't you? However, that isn't how Java syntax works.
calculatePay()
in Employee
is a void function, meaning it won't return any value. In this case, you want to have it return the netPay
of type double
. So instead, you should define the function as:
public double calculatePay() {
// code
netPay = grossPay - totalTax;
return netPay;
}
And in Company
you would just do
public calculatePay() {
for (int i = 0; i < noEmployees; i++) {
Employee employee = getEmployee(i);
System.out.println(employee.calculatePay());
}
}
Also, keep in mind this code is incomplete. If you also want calculatePay()
in Company
to return the total value or something, you would also need to change it's return type to double
.
I think your code should have two lists, one of employees and other of time cards.
public void calculatePay()
{
...
totalHoursWorked = getHoursWorked();
...
}
public void calculateEmployeesPay()
{
for(final Employee emp : EmployeeList)
{
emp.calculatePay();
}
}
public double getHoursWorked()
{
double totalHoursWorked = 0.0;
for (final TimeCard tc : TimeCardList)
{
totalHoursWorked += tc.getHoursWorked();
}
return totalHoursWorked;
}
if calculatePay() is void then netPay must changed to be an instance variable instead of a local.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.