包装学生类:
/** * @author Administrator * 学生类 */ public class Students { private String name; private char sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } public Students(String name, char sex) { super(); this.name = name; this.sex = sex; } }
学生类
测试类:
1 import java.util.Collections; 2 import java.util.HashMap; 3 import java.util.Iterator; 4 import java.util.Map; 5 import java.util.Scanner; 6 import java.util.Set; 7 8 public class Text01 { 9 static Scanner input= new Scanner(System.in); 10 public static void main(String[] args) { 11 Map<String, Students> student = new HashMap<String, Students>(); 12 student.put("Jack0", new Students("张三", ‘男‘)); 13 student.put("Jack1", new Students("李四", ‘女‘)); 14 student.put("Jack2", new Students("王五", ‘男‘)); 15 student.put("Jack3", new Students("赵六", ‘女‘)); 16 student.put("Jack4", new Students("钱七", ‘男‘)); 17 18 Set<String> keys = student.keySet(); 19 //遍历方法一:增强型for循环 20 for(String st:keys) { 21 Students value = student.get(st); 22 System.out.println(st+"---"+value.getName()+"---"+value.getSex()); 23 24 25 } 26 System.out.println("*****************************************"); 27 //遍历方法二:迭代器Iterator 28 Iterator<String> it = keys.iterator(); 29 while(it.hasNext()) { 30 String key1 = it.next(); 31 Students value1 = student.get(key1); 32 System.out.println(key1+"---"+value1.getName()+"---"+value1.getSex()); 33 } 34 35 //遍历方法三:键值对获取 36 System.out.println("*****************************************"); 37 for(Map.Entry<String, Students> map:student.entrySet()) { 38 String key = map.getKey(); 39 Students stu = map.getValue(); 40 System.out.println(key+"---"+stu.getName()+"---"+stu.getSex()); 41 } 42 43 44 System.out.println("您输入您要找的学员的英文名:"); 45 String name = input.next(); 46 if(student.containsKey(name)) { 47 Students stu = student.get(name); 48 System.out.println("您要找的英文名是"+name+"的学员中文名是:"+stu.getName()+" 性别为:"+stu.getSex()); 49 }else { 50 System.out.println("很抱歉,没有英文名是"+name+"的学员。"); 51 } 52 } 53 }
测试类
运行测试结果:
原文地址:https://www.cnblogs.com/Dean-0/p/11254266.html
时间: 2024-11-09 09:33:07