我有一个EmployeeStore
课程,用于存储公司员工的详细信息,例如姓名,身份证和电子邮件。我需要一种方法来通过其员工的电子邮件地址搜索hashmap,然后打印出具有匹配地址的个人员工。
我得到的代码是在另一个答案中搜索地图但无法设法打印员工。
这是我的代码:
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();
}
}
答案 0 :(得分:1)
您的searchByxxx
方法会返回Employee
,因此您应该阅读该值,然后很容易打印出来:
Employee james = Store.searchByName("James O' Carroll");
Employee andy = Store.searchByEmail("yahoo.com");
System.out.println(james);
System.out.println(andy);
您需要稍微清除searchByXXX
方法并删除不必要的打印语句。