使用java演示数组和方法存储和管理员工信息代码
时间: 2024-12-12 08:30:34 浏览: 16
在Java中,我们可以创建一个Employee类来表示员工信息,并通过数组和方法来管理一组员工。首先,我们定义一个Employee类,包含姓名、职位和薪水等属性:
```java
public class Employee {
private String name;
private String position;
private double salary;
// 构造函数
public Employee(String name, String position, double salary) {
this.name = name;
this.position = position;
this.salary = salary;
}
// 获取和设置属性的方法
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getPosition() { return position; }
public void setPosition(String position) { this.position = position; }
public double getSalary() { return salary; }
public void setSalary(double salary) { this.salary = salary; }
}
```
然后,我们可以创建一个ArrayList来存储Employee对象的数组,以及一个方法来添加、删除和显示员工信息:
```java
import java.util.ArrayList;
public class EmployeeManager {
private ArrayList<Employee> employees;
public EmployeeManager() {
employees = new ArrayList<>();
}
// 添加员工
public void addEmployee(Employee emp) {
employees.add(emp);
}
// 删除员工
public void removeEmployee(String name) {
employees.removeIf(employee -> employee.getName().equals(name));
}
// 显示所有员工信息
public void displayEmployees() {
for (Employee emp : employees) {
System.out.println("Name: " + emp.getName() + ", Position: " + emp.getPosition() + ", Salary: " + emp.getSalary());
}
}
}
// 示例用法
public static void main(String[] args) {
EmployeeManager manager = new EmployeeManager();
manager.addEmployee(new Employee("张三", "经理", 8000));
manager.addEmployee(new Employee("李四", "工程师", 6000));
manager.displayEmployees();
manager.removeEmployee("张三");
manager.displayEmployees();
}
```
阅读全文