自动点名器1:班级里有N个学生,实现随机点名器
public class test {public static void main(String [] args) {ArrayList<String> list=new ArrayList<>();//创建一个集合//在集合中添加元素Collections.addAll(list, "李明","王五","赵六","张三","李四","安然","杜若","范若","","倩倩");Random r=new Random();int index=r.nextInt(list.size());String name=list.get(index);System.out.println(name);}
}
自动点名器2:班级里有N个学生,要求:70%概率点到男生,30%概率点到女生。
分析:1)用一个【1,1,1,1,1,1,1,0,0,0】集合,打乱顺序,来获取随机索引,抽到1的概率为70%,抽到0的概率为30%。
2)创建男生集合,女生集合添加数据,判断索引值为1还是0,若为1在男生集合抽取,若为0在女生集合抽取。
public class test {public static void main(String [] args) {ArrayList<Integer> list=new ArrayList<>();//创建一个集合Collections.addAll(list, 1,1,1,1,1,1,1);Collections.addAll(list, 0,0,0);Collections.shuffle(list);//打乱顺序//获取随机索引Random r=new Random();int index=r.nextInt(list.size());int number=list.get(index);System.out.println(number);ArrayList<String> boy=new ArrayList<>();//男生集合Collections.addAll(boy, "李明","赵六","王五","安卓","李四","钱孙","史曾");ArrayList<String> girl=new ArrayList<>();//女生集合Collections.addAll(girl, "刘丽","范若","何怡");//判断索引为1还是0if(number==1) {int boyindex=r.nextInt(boy.size());//获取boy集合的随机索引System.out.println(boy.get(boyindex));}else {int girlindex=r.nextInt(girl.size());//获取girl集合的随机索引System.out.println(girl.get(girlindex));}}
}
自动点名器3:班级里有5个学生,要求:被点到的学生不会再被点到;但是如果班级中所有的学生都点完了,需要重新开启第二轮点名。
分析:1)被点到的学生不会再被点到,用remove移除集合中的元素,利用for循环保证将每位同学点到。
2)需要重新开启第二轮点名,用一个新集合保存旧集合的数据,remove移除完元素后,集合为空,将新集合数据赋给旧集合,利用for循环,定义开启第n次点名(假设点六次名)
public class test {public static void main(String [] args) {ArrayList<String> list=new ArrayList<>();//创建一个集合存放学生Collections.addAll(list, "李明","范若","王五","刘丽","史曾");Random r=new Random();int count=list.size();ArrayList<String> list1=new ArrayList<>();//第二个集合for(int j=0;j<=5;j++) {System.out.println("-------第"+(j+1)+"次点名--------");for(int i=0;i<count;i++) {int index=r.nextInt(list.size());String name=list.remove(index);//要保证被点到的同学不会再被点到,用remove移除集合元素list1.add(name);System.out.println(name);}list.addAll(list1);list1.clear();}}
}
集合嵌套:需求:定义一个Map集合,键用表示省份名称province,值表示市city,但是市会有多个。
添加完毕后,遍历结果格式如下:
江苏省=南京市,扬州市,苏州市,无锡市,常州市
湖北省=武汉市,孝感市,十堰市,宜昌市,鄂州市
河北省=石家庄市,唐山市,邢台市,保定市,张家口市
分析:值用单列集合存储。
public class test {public static void main(String [] args) {HashMap<String, ArrayList<String>> hm=new HashMap<>();ArrayList<String> city1=new ArrayList<>();Collections.addAll(city1, "南京市","扬州市","苏州市","无锡市","常州市");ArrayList<String> city2=new ArrayList<>();Collections.addAll(city2, "武汉市","孝感市","十堰市","宜昌市","鄂州市");ArrayList<String> city3=new ArrayList<>();Collections.addAll(city3, "石家庄市","唐山市","邢台市","保定市","张家口市");hm.put("江苏省", city1);hm.put("湖北省", city2);hm.put("河南省", city3);//利用entry遍历mapSet<Map.Entry<String, ArrayList<String>>> entries=hm.entrySet();for(Map.Entry<String, ArrayList<String>> entry:entries) {String key=entry.getKey();ArrayList<String> value=entry.getValue();StringJoiner sj=new StringJoiner(","," "," ");//传递标记,开始标记,结束标记for(String city:value) {sj.add(city);}System.out.println(key+" = "+sj);}}
}