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=0;i<num;i++){ list.add(i); } //打乱顺序 Collections.shuffle(list); } public void drawLotter(int n){ //产生N个指定范围(e-list.size())的随机数 Random rd = new Random(); for(int i=0;i<n;i++ ){ int index = rd.nextInt(list.size()); /*获得容器中以产生的随机数为下标的元素内容 * 即为获奖的奖券的抽奖号,输出 */ System.out .print(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.drawLotter(3); System.out.println("-----二等奖-----"); dr.drawLotter(10); System.out.println("-----三等奖-----"); dr.drawLotter(20); } }
时间: 2024-10-11 22:31:03