0

我有一个EmployeeStore类可以存储公司员工的详细信息,例如姓名、身份证和电子邮件。我需要一种方法来通过其员工的电子邮件地址搜索哈希图,然后打印出具有匹配地址的单个员工。

我得到了在另一个答案中搜索地图的代码,但无法打印员工。

这是我的代码:

public class EmployeeStore {

    HashMap<String, Employee> map;

    public EmployeeStore() {
        map = new HashMap<String, Employee>();
    }

    //....

    public void add(Employee employee) {
        map.put(employee.getEmployeeName(), employee);
    }

    public Employee searchByName(String name) {
        Employee employee = map.get(name);    
        System.out.println(employee);
        return employee;
    }

    public Employee searchByEmail(String email) {
        for (Employee employee : map.values()) {
            if (email.equals(employee.getEmployeeEmail())) {
                return employee;
            }
            System.out.println(employee);
        }
        Employee employee = map.get(email);
        System.out.println(employee);

        return employee;
    }
}

为此,我将代码更改为:

public Employee searchByEmail(String email) 
    {
        for (Employee employee : map.values())
        {
            if (email.equals(employee.getEmployeeEmail()))
            {
                System.out.println(employee);
                return employee;
            }
        }


        return null;
    }

主要的:

public class MainApp {

    private static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args) {
        new MainApp().start();
    }

    public void start() {
        EmployeeStore Store = new EmployeeStore();
        Store.add(new Employee("James O' Carroll", 18, "hotmail.com"));

        Store.add(new Employee("Andy Carroll", 1171, "yahoo.com"));

        Store.add(new Employee("Luis Suarez", 7, "gmail.com"));
        Store.searchByName("James O' Carroll");
        //Store.print();
    }
}
4

1 回答 1

1

您的searchByxxx方法返回 anEmployee因此您应该读取该值然后很容易打印它:

Employee james = Store.searchByName("James O' Carroll");
Employee andy = Store.searchByEmail("yahoo.com");

System.out.println(james);
System.out.println(andy);

并且您需要searchByXXX稍微清理方法并删除不必要的打印语句。

于 2012-07-02T16:13:31.747 回答