Java – an alternative to if else statements when using double precision
•
Java
According to the salary, I need to assign a specific tax rate to the employee object Salary is defined by annual salary, which is a double, so I can't use switch statement I use if / else instead:
public int getSalaryRank() { if(yearlySalary <= 60000.00) { salaryRank = 1; } else if(yearlySalary > 60000.00 && yearlySalary <= 80000.00) { salaryRank = 2; } else if(yearlySalary > 80000.00 && yearlySalary <= 100000.00) { salaryRank = 3; } else if(yearlySalary > 100000.00 && yearlySalary <= 125000.00) { salaryRank = 4; } else { salaryRank = 5; } return salaryRank; }
I will distribute the tax rate later according to the ranking Is there a better way to write this?
Solution
You can simplify it like this:
public int getSalaryRank() { int salaryRank; if(yearlySalary <= 60000.00) { return 1; } if(yearlySalary <= 80000.00) { return 2; } if(yearlySalary <= 100000.00) { return 3; } if(yearlySalary <= 125000.00) { return 4; } return 5 }
All checks on the left are unnecessary because the statements are executed sequentially In addition, you can delete the else statement and return directly to salarybank In addition, never use floating point numbers when dealing with money Use BigDecimal instead
Editor: Considering @ Alex Wien's comments on multiple exit points, this may be a better solution:
public int getSalaryRank() { if(yearlySalary <= 60000.00) { salaryRank = 1; } else if(yearlySalary <= 80000.00) { salaryRank = 2; } else if(yearlySalary <= 100000.00) { salaryRank = 3; } else if(yearlySalary <= 125000.00) { salaryRank = 4; } else { salaryRank = 5; } return salaryRank; }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码