带有概率的随机点名

image
1111111000,随机抽取,抽到1点名男生,抽到0点名女生。

点击查看代码
public class Test2 {
    public static void main(String[] args) {
        //按概率点名,男生抽到的概率为0.7,女生抽到的概率为0.3
        //1.创建集合
        ArrayList<Integer> list = new ArrayList<>();
        //2.添加数据
        Collections.addAll(list, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0);
        //3.打乱集合中的数据
        Collections.shuffle(list);
        //4.从list中随机抽取0或1
        Random r = new Random();
        int index = r.nextInt(list.size());
        int number = list.get(index);

        //5.创建两个集合存储名字
        ArrayList<String> boyList = new ArrayList<>();
        ArrayList<String> girlList = new ArrayList<>();

        Collections.addAll(boyList, "张吉惟","林国瑞","林玟书","林雅南","江奕云","刘柏宏", "阮建安");
        Collections.addAll(girlList, "林子帆","夏志豪","吉茹定","李中冰","黄文隆");

        if (number == 1) {
            //1点名男生
            int boyIndex = r.nextInt(boyList.size());
            System.out.println(boyList.get(boyIndex));
        }else {
            //0点名女生
            int girlIndex = r.nextInt(girlList.size());
            System.out.println(girlList.get(girlIndex));
        }

    }
}
posted @ 2025-09-05 17:48  lachii  阅读(24)  评论(0)    收藏  举报