在h.getNetYearlyIncome()失败,似乎是5k太高了。我整天都在努力,无法理解。
为什么h.getNetYearlyIncome()= h.getGrossYearlyIncome() - h.getTaxesWithheld() 不等于annualIncome-taxesWitheld
public void testSalariedEmployeeMakingOver100K() {
SalariedEmployee h = new SalariedEmployeeImpl("John", "Doe", "Mechanical Turk", 1111, 9166.75);
assertEquals(h.getFirstName(), "John");
assertEquals(h.getLastName(), "Doe");
assertEquals(h.getJobTitle(), "Mechanical Turk");
assertEquals(h.getID(), 1111);
assertEquals(h.getMonthlySalary(), 9166.75, 0.005);
assertEquals(h.getGrossYearlyIncome(), 9166.75*12, 0.005);
assertEquals(h.getTaxableIncome(), h.getGrossYearlyIncome(), 0.005);
assertEquals(h.getTaxesWithheld(), 15000.25, 0.005);
assertEquals(h.getNetYearlyIncome(), h.getGrossYearlyIncome()-h.getTaxesWithheld(), 0.005);
}
public class SalariedEmployeeImpl extends EmployeeImpl implements
SalariedEmployee {
String first_name;
String last_name;
String job_title;
int id;
double monthly_salary = 0.0;
double yearlyIncome = 0.0;
double taxableIncome = 0.0;
double netIncome = 0.0;
double taxesWitheld = 0.0;
double over100k = 0.0;
double over50k= 0.0;
SalariedEmployeeImpl(String first_name, String last_name, String job_title,
int id, double monthly_salary) {
this.first_name = first_name;
this.last_name = last_name;
this.job_title = job_title;
this.id = id;
this.monthly_salary = monthly_salary;
}
public String getFirstName() {
return first_name;
}
public String getLastName() {
return last_name;
}
public String getJobTitle() {
return job_title;
}
public int getID() {
return id;
}
public double getGrossYearlyIncome() {
yearlyIncome = (monthly_salary * 12);
return yearlyIncome;
}
public double getTaxableIncome() {
taxableIncome = (monthly_salary*12);
return taxableIncome;
}
public double getTaxesWithheld() {
double over100k = 0.0;
double over50k= 0.0;
if(taxableIncome>100000.0){
over100k = taxableIncome -100000.0;
taxableIncome -=over100k;
}
if(taxableIncome >50000.0 && taxableIncome <=100000.0){
over50k = taxableIncome-50000.0;
taxableIncome -=over50k;
}
taxesWitheld = taxesWitheld + (.15 * over50k)+(.25 * over100k)+(.1*taxableIncome);
return taxesWitheld ;
}
public double getNetYearlyIncome() {
return yearlyIncome-taxesWitheld;
}
public double getMonthlySalary() {
return monthly_salary;
}
public void setMonthlySalary(double salary) {
this.monthly_salary = salary;
}
}
答案 0 :(得分:4)
您的函数getGrossYearlyIncome
不仅仅是一个getter函数 - 它初始化yearlyIncome
。在您调用该函数之前,yearlyIncome
的值为0.但是,getNetYearlyIncome
使用yearlyIncome
但未调用getGrossYearlyIncome
,因此yearlyIncome
未正确初始化被称为第一。
您遇到与getTaxableIncome
和getTaxesWithheld
类似的问题 - 他们不仅会获得一个值,还会在调用时初始化成员字段。