首先根据题目要求,新建三个employee对象。因为题目预设代码已经给出Employee的有参构造方法,所以我们可以通过有参构造的方式新建employee对象,然后通过List集合的add方法,将employee对象放入集合中。 此处参考代码如下:
Employee employee1 = new Employee("小明",2500);
Employee employee2 = new Employee("小军",8000);
Employee employee3 = new Employee("小红",100000);
employees.add(employee1);
employees.add(employee2);
employees.add(employee3);
之后我们就可以通过遍历集合来对集合中元素进行操作,首先我们定义double类型的个人所得税变量以及应纳税额变量,使用if,if else语句,对每个工资等级进行划分并按照表格中给出的计算方法进行计算。因为逻辑在集合遍历中实现,所以在输出时应该首先获得当前集合中的employee对象,使用getName()方法得到当前对象的姓名属性,按照题目要求格式输出该对象的个人所得税,这部分逻辑的代码参考写法为:
for (int i = 0; i < employees.size(); i++) {
double tax = 0.0;
double taxIncome = employees.get(i).getSalary() - 3500;
if (taxIncome <= 0) {
tax = 0.0;
} else if (taxIncome <= 1500) {
tax = taxIncome * 0.03;
} else if (taxIncome <= 4500) {
tax = taxIncome * 0.10 - 105;
} else if (taxIncome <= 9000) {
tax = taxIncome * 0.20 - 555;
} else if (taxIncome <= 35000) {
tax = taxIncome * 0.25 - 1005;
} else if (taxIncome <= 55000) {
tax = taxIncome * 0.30 - 2755;
} else if (taxIncome <= 80000) {
tax = taxIncome * 0.35 - 5505;
} else {
tax = taxIncome * 0.45 - 13505;
}
System.out.println(employees.get(i).getName()+"应该缴纳的个人所得税是:" + tax);
}
附上完整代码:
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
//write your code here......
Employee employee1 = new Employee("小明",2500);
Employee employee2 = new Employee("小军",8000);
Employee employee3 = new Employee("小红",100000);
employees.add(employee1);
employees.add(employee2);
employees.add(employee3);
for (int i = 0; i < employees.size(); i++) {
double tax = 0.0;
double taxIncome = employees.get(i).getSalary() - 3500;
if (taxIncome <= 0) {
tax = 0.0;
} else if (taxIncome <= 1500) {
tax = taxIncome * 0.03;
} else if (taxIncome <= 4500) {
tax = taxIncome * 0.10 - 105;
} else if (taxIncome <= 9000) {
tax = taxIncome * 0.20 - 555;
} else if (taxIncome <= 35000) {
tax = taxIncome * 0.25 - 1005;
} else if (taxIncome <= 55000) {
tax = taxIncome * 0.30 - 2755;
} else if (taxIncome <= 80000) {
tax = taxIncome * 0.35 - 5505;
} else {
tax = taxIncome * 0.45 - 13505;
}
System.out.println(employees.get(i).getName()+"应该缴纳的个人所得税是:" + tax);
}
}
}
class Employee{
private String name;
private int salary;
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public int getSalary() {
return salary;
}
}