Java实现抽奖功能
商城项目开发中经常会有抽奖这样的活动的需求,这里介绍一种简单的抽奖方式
public static void main(String[] argc) throws Exception {
//定义一个集合list,可以是用户id,也可以是抽奖号码之类的
List<Long> list = new ArrayList<Long>();//用户id集合
list.add(10L);
list.add(11L);
list.add(12L);
list.add(13L);
list.add(14L);
list.add(15L);
list.add(16L);
list.add(17L);
List <Long> userId = new ArrayList<>();
Random random = new Random();
// 定义一个数组用于存放需要抽奖的名单(长度为参与抽奖的人数)
Long[] name = new Long[list.size()];
for (int i = 0;i < name.length;i++) {
//循环录入
name[i] = list.get(i);
}
//想要抽取的人数(即中奖名额)
int renShu = 5;
int index = 0;
//定义新int数组shuZi
int[] shuZi = new int[renShu];
//选出想要选的人数
while(index < renShu){
int num = random.nextInt(name.length);
//当不相同时,实现给shuZi数组赋值,给index自加一,打印输出name数组
if(!judge(shuZi,num)){
shuZi[index ++] = num;
System.out.println("中奖结果====="+name[num]);
userId.add(name[num]);
}
}
System.out.println("中奖结果集合====="+userId);
}
public static boolean judge(int shuZi2[], int key){
for(int i = 0;i < shuZi2.length;i ++){
if(shuZi2[i] == key){
return true;
}
}
return false;
}
运行结果:
这样就ok了