Employee/EmployeeTest.java
Employee.java
import java.time.LocalDate;
public class Employee {
// 3个字段,用来存放将要操作的数据
private final String name;
private double salary;
private LocalDate hireDay;
// 通过Generate...生成后修改
public Employee(String name, double salary, int year, int month, int day) {
this.name = name;
this.salary = salary;
hireDay = LocalDate.of(year, month, day);
}
// 通过Generate...生成即可
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public LocalDate getHireDay() {
return hireDay;
}
// 自己写
public void raiseSalary(double byPercent) {
double raise = salary * byPercent / 100;
salary += raise;
}
}
EmployeeTest.java
public class EmployeeTest {
public static void main(String[] args) {
Employee[] staff = new Employee[3]; // 对象数组
staff[0] = new Employee("张三", 1000, 2020, 3, 15);
staff[1] = new Employee("李四", 2000, 2019, 9, 18);
staff[2] = new Employee("王五", 5000, 2023, 1, 1);
for (Employee e : staff) { // for each循环
e.raiseSalary(5);
String tmp = "name=" + e.getName() +
", salary=" + e.getSalary() +
", hireDay=" + e.getHireDay();
System.out.println(tmp);
}
}
}
输出:
name=张三, salary=1050.0, hireDay=2020-03-15
name=李四, salary=2100.0, hireDay=2019-09-18
name=王五, salary=5250.0, hireDay=2023-01-01
计算时间差
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class MyTest {
public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2023, 9, 23);
System.out.println(date1); // => 2023-09-23
LocalDate date2 = LocalDate.of(2024, 9, 22);
System.out.println(date2); // => 2024-09-22
// 计算天数差1
long result1 = date2.toEpochDay() - date1.toEpochDay();
// 计算天数差2
long result2 = ChronoUnit.DAYS.between(date1, date2);
// 计算月数差
long result3 = ChronoUnit.MONTHS.between(date1, date2);
System.out.println(result1); // => 365
System.out.println(result2); // => 365
System.out.println(result3); // => 11
// 说明:23.9.23到24.9.23才算完整的12个月,23.9.23到24.9.22不足12个月,按11个月计算
}
}
仅供参考,可采用其它任意方式。
Employee改进版_测试
public class EmployeeTest {
public static void main(String[] args) {
Employee[] staff = new Employee[3]; // 对象数组
staff[0] = new Employee("张三", 1000, 2024, 8, 24);
staff[1] = new Employee("李四", 1000, 2023, 9, 23);
staff[2] = new Employee("王五", 1000, 2022, 9, 23);
for (Employee e : staff) { // for each循环
String tmp = "name=" + e.getName() +
", 总报酬=" + e.getTotalSalary() +
", 总天数=" + e.getDaysSinceHire();
System.out.println(tmp);
}
}
}
输出(24年9月23日):
name=张三, 总报酬=0.0, 总天数=30
name=李四, 总报酬=12000.0, 总天数=366
name=王五, 总报酬=24000.0, 总天数=731