Java Reference
In-Depth Information
This solution is clear and concise but not efficient. For instance, if the taxable salary amount is less than 50, the tax
amount is set to zero but the three succeeding if conditions are still executed. We want the computer to ignore the
other comparisons after the tax amount is determined. This can be done by nesting the ifs.
Nesting ifs means that an if statement is placed within another if statement. In this case we will add else keywords
to the first three if s and place each succeeding if inside the previous else clause. For instance, the first if condition
checks if the amount is less than 50. Only if this condition is false do we want the computer to check the other
conditions. So we add an else clause and place the next if inside the else as follows:
if (taxSal <= 50)
taxAmt = 0;
else {
if ((taxSal > 50) && (taxSal <= 150))
taxAmt = taxSal - 50 * .12;}
Now, only when the tax salary amount is greater than 50 will the second condition be tested. We also only want
to check the third condition when the second is false and the fourth condition only when the third is false. So, we will
nest those if s as follows:
if (taxSal <= 50)
taxAmt = 0;
else {
if ((taxSal > 50) && (taxSal <= 150))
taxAmt = taxSal - 50 * .12;
else {
if ((taxSal > 150) && (taxSal <= 550))
taxAmt = 12 + taxSal - 150 * .15;
else {
if ((taxSal > 550) && (taxSal <= 1150))
taxAmt = 72 + taxSal - 550 * .25;
else
taxAmt = 222 + taxSal - 1150 * .28;
}
}
}
This source code matches the logic shown in Figure 6-1 .
Notice how the indentation helps identify under which condition the taxAmt calculation will be performed.
This will help when trying to debug the application.
If you were really trying to improve efficiency, you would research the employee pay rates and determine which
salary ranges were the most prevalent and arrange the order of the conditions so the most frequent salary range was
checked first, then the second most, third most, and so on. This would reduce the number of conditions tested even
further. Of course, the code would be much more difficult to understand and, if there were problems, harder to debug.
Tutorial: Tax Calculation—Part II
With the above discussion in mind, we will take the middle ground between efficiency and understandability and
implement the nested if s as above.
1.
Replace the if condition in fedTaxCalc with the nested if s as above.
2.
Click to the right of the brace on the first else statement.
 
Search WWH ::




Custom Search