第一题
1 package com.kgc.zjlx.zj1.zj101; 2 3 import java.util.*; 4 5 public class HashMapDemo { 6 public static void main(String[] args){ 7 Scanner sc=new Scanner(System.in); 8 Map<String,Integer> map=new HashMap(); 9 10 map.put("张三",89); 11 map.put("李四",59); 12 map.put("王五",61); 13 14 System.out.print("请输入学生姓名:"); 15 String name=sc.next(); 16 if (map.containsKey(name)) { 17 System.out.println(name + "的成绩是:" + map.get(name)); 18 }else{ 19 System.out.println(name+"学员不存在"); 20 } 21 System.out.println("-------所有学生的成绩是-------"); 22 Set<String> set=map.keySet(); //返回键的集合 23 for (String s:set){ 24 System.out.println(s+"的成绩是:"+map.get(s)); //根据键输出对应的值 25 } 26 27 } 28 }
运行结果
第二题
1 package com.kgc.zjlx.zj1.zj102; 2 3 import java.util.*; 4 5 public class ArrayListDemo { 6 public static void main(String[] args) { 7 Scanner sc = new Scanner(System.in); 8 9 List<Student> list = new ArrayList(); 10 Map<String, List> map = new HashMap(); 11 list.add(new Student("张三丰")); 12 list.add(new Student("杨过")); 13 list.add(new Student("郭靖")); 14 map.put("三年级一班", list); 15 System.out.print("输入班级名称:"); 16 String banji = sc.next(); 17 18 if (map.containsKey(banji)) { //判断是否有输入的班级 19 System.out.println(banji + "学生列表:"); 20 //通过迭代器获得集合元素 21 Iterator<Student> itor = list.iterator(); 22 while (itor.hasNext()) { 23 Student str = itor.next(); 24 System.out.println(str.getName()); 25 } 26 //返回值的集合 27 // Collection<List> c=map.values(); 28 // for (int i=0;i<list.size();i++){ 29 // System.out.println(list.get(i).getName()); 30 } 31 } else { 32 System.out.println("输入的班级不存在"); 33 } 34 35 } 36 }
运行结果
第三题
1 package com.kgc.zjlx.zj1.zj103; 2 3 import java.util.*; 4 5 public class MapDemo { 6 public static void main(String[] args){ 7 Scanner sc=new Scanner(System.in); 8 ArrayList<Student> list=new ArrayList<>(); 9 Map<String,ArrayList<Student>> map=new HashMap<>(); 10 Student stu1=new Student("张三丰","男",18); 11 Student stu2=new Student("杨过","男",19); 12 Student stu3=new Student("郭靖","女",20); 13 14 list.add(stu1); 15 list.add(stu2); 16 list.add(stu3); 17 map.put("三年级一班",list); 18 19 System.out.print("输入班级名称:"); 20 String banji=sc.next(); 21 if (map.containsKey(banji)){ 22 System.out.println(banji+"学生列表:"); 23 System.out.println("------------"); 24 25 Iterator<Student> ito=list.iterator(); 26 while (ito.hasNext()){ 27 Student stu=ito.next(); 28 System.out.println(stu.getName()+"\t\t"+stu.getSex()+"\t"+stu.getAge()); 29 } 30 }else{ 31 System.out.println("班级不存在"); 32 } 33 34 } 35 }
运行结果