private String name; private int age; private BigDecimal salary; private Date hireDate; public EmployeeString name int age BigDecimal salary Date hireDate thisn
这段代码已经相对简化了,但仍然可以进一步精简。以下是精简后的代码:
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Employee {
private String name;
private int age;
private BigDecimal salary;
private Date hireDate;
public Employee(String name, int age, BigDecimal salary, Date hireDate) {
this.name = name;
this.age = age;
this.salary = salary;
this.hireDate = hireDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public Date getHireDate() {
return hireDate;
}
public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}
public static void main(String[] args) throws ParseException {
String data = "name=小红&age=17&salary=8000.00&hireDate=1991-07-03;" +
"name=小明&age=23&salary=10000.00&hireDate=1992-12-11;" +
"name=小白&age=18&salary=12000.00&hireDate=1996-01-09";
String[] employeesData = data.split(";");
List<Employee> employees = new ArrayList<>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
for (String employeeData : employeesData) {
String[] attributes = employeeData.split("&");
String name = attributes[0].split("=")[1];
int age = Integer.parseInt(attributes[1].split("=")[1]);
BigDecimal salary = new BigDecimal(attributes[2].split("=")[1]);
Date hireDate = dateFormat.parse(attributes[3].split("=")[1]);
employees.add(new Employee(name, age, salary, hireDate));
}
BigDecimal totalSalary = BigDecimal.ZERO;
for (Employee employee : employees) {
if (employee.getHireDate().before(dateFormat.parse("1996-01-01"))) {
totalSalary = totalSalary.add(employee.getSalary());
}
}
BigDecimal averageSalary = totalSalary.divide(BigDecimal.valueOf(employees.size()), 2, BigDecimal.ROUND_HALF_UP);
System.out.println("1996 年前入职的员工的平均薪资为: " + averageSalary);
}
}
在精简后的代码中,主要的变化包括:
- 移除了不必要的计数变量
count,使用employees.size()获取员工数量。 - 在循环中直接解析日期字符串并创建
Date对象,不再需要额外的try-catch块。 - 在计算平均薪资时,直接使用
employees.size()作为总员工数,避免了额外的循环来计算数量
原文地址: https://www.cveoy.top/t/topic/ihsI 著作权归作者所有。请勿转载和采集!