班级里有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();
}
}
}