1.简单点名器
需求:假设班级有N个学生,实现简单随机点名器
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class Test1 {
public static void main(String[] args) {
// 1.定义集合
ArrayList<String> list=new ArrayList<>();
// 添加数据
Collections.addAll(list,"范闲","范建","笵统","滕子健","梅长苏","李克","左道");
// 随机点名
/* Random r=new Random();
int index=r.nextInt(list.size());
System.out.println(list.get(index));*/
Collections.shuffle(list);
System.out.println(list.get(0));
}
}
2.概率点名器
需求:班级有N个学生,要求70%概率随机到男生,30概率随机到女生
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class Test2 {
public static void main(String[] args) {
// 1、创建集合
ArrayList<Integer> list=new ArrayList<>();
// 添加数据
Collections.addAll(list,1,1,1,1,1,1,1);
Collections.addAll(list,0,0,0);
// 打乱集合中的数据
Collections.shuffle(list);
System.out.println(list);
// 从list集合中随机抽取0或者1
Random r=new Random();
int index=r.nextInt(list.size());
int number=list.get(index);
System.out.println(number);
// 创建两个集合分别存储男生和女生的名字
ArrayList<String> man=new ArrayList<>();
ArrayList<String> woman=new ArrayList<>();
Collections.addAll(man,"范闲","范建","笵统","滕子健","梅长苏","李克","左道");
Collections.addAll(woman,"霓凰","三三","四四","五五");
// 判断此时从man中抽取海事从woman中抽取
if (number==1){
// 男生
int manindex=r.nextInt(man.size());
String name=man.get(manindex);
System.out.println(name);
}else {
// 女生
int womanindex=r.nextInt(woman.size());
String name=man.get(womanindex);
System.out.println(name);
}
}
}
3.循环点名器
需求:班级有N个学生,被点到的学生不会再被点到。如果班级中所有学生都点完了,需要重新开始第二轮点名
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> list1=new ArrayList<>();
// 随机点名
Random r=new Random();
for (int j = 1; j <= 10; j++) { //重复10轮
System.out.println("第"+j+"轮点名开始了");
int count=list.size();
for (int i = 0; i < count; i++) {
int index=r.nextInt(list.size());
// String name=list.get(index);
// list.remove(index);
String name=list.remove(index);
list1.add(name);
System.out.println(name);
}
//此时表明一轮点名结束
// list中集合为空,现在将list1中元素全部添加到list中
list.addAll(list1);
list1.clear();
}
}
}