用Java编写一个程序将当前目录下所有的员工文件进行读取并解析出所有员工为Emp 对象并存入Map。其中key为该员工的名字value为该员工的emp对象。 然后要求用户输入一个员工名字若该员工存在则输出该员工的名字年龄工资以及入职20周年的纪念日当周的周六的日期。 即输入名字张三 若该员工存在则输出如下格式 张三2550002006-02-14
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Map; import java.util.Scanner;
public class EmployeeProgram {
public static void main(String[] args) {
// 获取当前目录下所有员工文件
File directory = new File(".");
File[] files = directory.listFiles((dir, name) -> name.endsWith(".txt"));
// 创建员工Map
Map<String, Employee> employeeMap = new HashMap<>();
// 读取并解析员工文件
for (File file : files) {
Employee employee = parseEmployeeFile(file);
if (employee != null) {
employeeMap.put(employee.getName(), employee);
}
}
// 用户输入员工名字
Scanner scanner = new Scanner(System.in);
System.out.print("请输入员工名字: ");
String name = scanner.nextLine();
// 查找员工并输出信息
Employee employee = employeeMap.get(name);
if (employee != null) {
System.out.println(employee.getName() + "," + employee.getAge() + "," + employee.getSalary() + "," + employee.getJoinDate());
LocalDate anniversaryDate = employee.getJoinDate().plusYears(20);
LocalDate saturday = getNextSaturday(anniversaryDate);
System.out.println("入职20周年纪念日派对日期: " + saturday);
} else {
System.out.println("查无此人");
}
}
private static Employee parseEmployeeFile(File file) {
try (FileInputStream fis = new FileInputStream(file);
Scanner scanner = new Scanner(fis)) {
String name = scanner.nextLine();
int age = Integer.parseInt(scanner.nextLine());
double salary = Double.parseDouble(scanner.nextLine());
String joinDateStr = scanner.nextLine();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate joinDate = LocalDate.parse(joinDateStr, formatter);
return new Employee(name, age, salary, joinDate);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static LocalDate getNextSaturday(LocalDate date) {
LocalDate nextSaturday = date;
while (nextSaturday.getDayOfWeek() != DayOfWeek.SATURDAY) {
nextSaturday = nextSaturday.plusDays(1);
}
return nextSaturday;
}
}
class Employee { private String name; private int age; private double salary; private LocalDate joinDate;
public Employee(String name, int age, double salary, LocalDate joinDate) {
this.name = name;
this.age = age;
this.salary = salary;
this.joinDate = joinDate;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getSalary() {
return salary;
}
public LocalDate getJoinDate() {
return joinDate;
}
原文地址: https://www.cveoy.top/t/topic/hy9H 著作权归作者所有。请勿转载和采集!