嵌套if语句有问题

时间:2013-04-13 19:32:15

标签: java nested

理论是,不同的收入等级的税率百分比不同。 10%前50k,15%下一个50k,25%超过10万。

 public double getTaxesWithheld() {

    if (taxableIncome >= 100000.0) {

        taxesWitheld = taxesWitheld+ (.25 * (taxableIncome - 100000.0));
        taxableIncome = taxableIncome - 100000.0;
    } else {
        if (taxableIncome >= 50000.0 && taxableIncome <= 100000.0) {
            taxesWitheld = taxesWitheld + (.15 * (taxableIncome - 50000.0));
            taxableIncome = taxableIncome - 50000.0;
        } else {
            if (taxableIncome < 50000.0) {
                taxesWitheld = taxesWitheld + (.1 * (taxableIncome - 25000.0));
            }
        }

        if (taxableIncome <= 0) {
            return 0.0;
        }

    }
    return taxesWitheld;
}

测试案例1:     @测试 构造函数值(first_name,last_name,job_title,id,monthly_salary)

public void EmployeeMakingBetween50Kand100K() {
    Employee h = new EmployeeImpl("Jon", "Smith", "Miner", 2222, 6166.75);


    assertEquals(h.getMonthlySalary(), 6166.75, 0.005);
    assertEquals(h.getGrossYearlyIncome(), 6166.75*12, 0.005);
    assertEquals(h.getTaxableIncome(), h.getGrossYearlyIncome(), 0.005);
    assertEquals(h.getTaxesWithheld(), 8600.15, 0.005);
    assertEquals(h.getNetYearlyIncome(), h.getGrossYearlyIncome()-h.getTaxesWithheld(), 0.005);
}

不会处理taxWithheld(),8600.15,0.005

3 个答案:

答案 0 :(得分:3)

这是一种完全不同的方法,可能会产生更好的结果:

 public double getTaxesWithheld() {

    over100k = Math.max(taxableIncome-100000, 0);
    taxableIncome -= over100k;
    over50k = Math.max(taxableIncome-50000, 0);
    taxableIncome -= over50k;

    taxesWitheld = taxesWitheld + (.25 * over100k);
    taxesWitheld = taxesWitheld + (.15 * over50k);
    taxesWitheld = taxesWitheld + (.1 * taxableIncome);
    return taxesWitheld;
}

答案 1 :(得分:2)

你的嵌套有点不稳定

if (taxableIncome >= 100000.0) {
    ...
} else if (taxableIncome >= 50000.0) { 
// you don't need if(<= 100000), it's implied since you already 
// know it's !(taxableIncome >= 1000000) from the first if statement
    ...
} else if (taxableIncome > 0) {
    ...
} else return 0; 
// again, you don't need if(<= 0) here, 
// it's implied since you know that !(taxableIncome > 0)

答案 2 :(得分:1)

不应该是if else语句,因为在减去100k之后仍然需要对其余部分征税。

if (taxableIncome >= 100000.0) {
    taxesWitheld = taxesWitheld+ (.25 * (taxableIncome - 100000.0));
    taxableIncome = taxableIncome - 100000.0;
}

if (taxableIncome >= 50000.0 && taxableIncome <= 100000.0) {
        taxesWitheld = taxesWitheld + (.15 * (taxableIncome - 50000.0));
        taxableIncome = taxableIncome - 50000.0;
}