import java.util.ArrayList; import java.util.Collections; import java.util.Random; public class Draw { private ArrayList<Integer> list; public Draw(){ list = new ArrayList<Integer>(); } public void deal(int num){ //向容器中添加奖券(使用循环) for(int i = 1;i < num;i++){ list.add(i); } //打乱顺序 Collections.shuffle(list); } public void drawLottery(int n){ //产生n个指定范围(0-list.size())的随机数 Random l = new Random(); for(int i = 0;i < n;i++){ int index = l.nextInt(list.size()); //获得容器中以产生的随机数为下标的元素的内容,即为获奖的奖券的抽奖号,输出 System.out.println(list.get(index)+"\t"); //将已获奖的元素(奖券)从容器总删除 list.remove(index); } System.out.println(); } public static void main(String[] args) { // TODO Auto-generated method stub Draw dr = new Draw(); dr.deal(2000); System.out.println("------一等奖------"); dr.drawLottery(5); System.out.println("------二等奖------"); dr.drawLottery(10); System.out.println("------三等奖------"); dr.drawLottery(15); } }
时间: 2024-10-10 00:16:00