概率型随机点名(JAVA版)

需求:实现随机点名,男生概率70%,女生30%;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

public class test2 {
    public static void main(String[] args) {
        ArrayList list = new ArrayList<>();
        Collections.addAll(list, 1, 1, 1, 1, 1, 1, 1);//Collections集合工具类,
        Collections.addAll(list, 0, 0, 0);//addAll(Collection,T...elements>批量添加元素
        //方法一
       /* Collections.shuffle(list);//void shuffle(List list)打乱集合中的元素顺序
        int x = list.get(0);*/
        //方法二
        Random r = new Random();
        int index = r.nextInt(list.size());//根据随机数获取索引
        int key = list.get(index);//获取索引对应的值

        ArrayList grillist = new ArrayList<>();
        ArrayList boylist = new ArrayList<>();
        Collections.addAll(boylist, "张男", "张大男", "张小男", "陈男", "周男", "刘男");//.addAll批量添加元素
        Collections.addAll(grillist, "张女", "陈女", "周女", "刘女", "李女", "王女");
        if (key == 1) {
            int index1 = r.nextInt(boylist.size());
            String boyname = boylist.get(index1);
            System.out.println(boyname);
        } else {
            int index2 = r.nextInt(grillist.size());
            String girlname = grillist.get(index2);
            System.out.println(girlname);
        }

    }
}

你可能感兴趣的:(java,python,windows)