1. package Student;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import java.util.Scanner;
  5. class Student {
  6. private String name;
  7. private String sex;
  8. public Student(){}
  9. public Student(String name, String sex) {
  10. super();
  11. this.name = name;
  12. this.sex = sex;
  13. }
  14. public String getName() {
  15. return name;
  16. }
  17. public void setName(String name) {
  18. this.name = name;
  19. }
  20. public String getSex() {
  21. return sex;
  22. }
  23. public void setSex(String sex) {
  24. this.sex = sex;
  25. }
  26. }
  27. public class Text {
  28. public static void main(String[] args) {
  29. Map<String,Student> students =new HashMap<String,Student>();//泛型使用后无需强转
  30. //键值对:学院的英文名字 --学员
  31. students.put("jack", new Student("张三","男"));
  32. students.put("Tom", new Student("李四","男"));
  33. students.put("kitty", new Student("王五","女"));
  34. //跟库相应的key得到相应的值
  35. Scanner sc=new Scanner(System.in);
  36. System.out.println("请输入您要找的英文名:");
  37. String key = sc.next();
  38. if(students.containsKey(key)){ //判断是否存在此键
  39. Student stu=students.get(key); //根据拿到的键key获得对应的值给stu对象
  40. System.out.println("您要找的学员是:"+stu.getName()+"--"+stu.getSex());//取值
  41. }else{
  42. System.out.println("对不去,没有找到您要的学员");
  43. }
  44. }
  45. }
文档更新时间: 2020-11-04 13:13   作者:mlrs