本文主要是介绍自动点名器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
班级里有N个学生,实现随机点名器
package MyApi.a00test;import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;public class Test1 {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);*///第二种Collections.shuffle(list);String name=list.get(0);System.out.println(name);}
}
班级里面有N个学生
要求:70%的概率随机到男生,30%的概率随机到女生
package MyApi.a00test;import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;public class Test2 {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());Integer number = list.get(index);System.out.println(number);ArrayList<String> boylist=new ArrayList<>();ArrayList<String> girllist=new ArrayList<>();Collections.addAll(boylist,"王俊凯","王源","易烊千玺","夏之光","黄俊捷","肖战","王一博");Collections.addAll(girllist,"杨幂","迪丽热巴","娜扎");if(number==1){int boyindex = r.nextInt(boylist.size());String boyname = boylist.get(boyindex);System.out.println(boyname);}else {int girlindex = r.nextInt(girllist.size());String girlname= boylist.get(girlindex);System.out.println(girlname);}}
}
要求:
被点到的学生不会在被点到,但是如果班级中所有的学生都点完了,需要重新开启第二轮点名
package MyApi.a00test;import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;public class Test3 {public static void main(String[] args) {ArrayList<String> list=new ArrayList<>();Collections.addAll(list,"王俊凯","王源","易烊千玺","夏之光","黄俊捷","肖战","王一博","杨幂","迪丽热巴","娜扎");//创建一个临时的集合,用来存储已经被点到名字的学生ArrayList<String> list2=new ArrayList<>();for (int i = 0; i < 10; i++) {int count= list.size();Random r=new Random();for (int j = 0; j < count; i++) {int index = r.nextInt(list.size());/* String name = list.get(index);list.remove(name);*/String name = list.remove(index);list2.add(name);System.out.println(name);}//此时表示一轮集合已经结束list.addAll(list2);list2.clear();}}
}
这篇关于自动点名器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!