zoukankan      html  css  js  c++  java
  • Java(六)——抽奖系统

     总体思路:

          将编号加入ArrayList动态数组中,利用集合的静态方法Collections.shuffle() 乱序集合中的元素从而获得随机数,remove删除已抽编号

     代码如下:

     1 import java.util.ArrayList;
     2 import java.util.Collections;
     3 import java.util.Random;
     4 
     5 public class raffle {
     6 
     7     private ArrayList<Integer> list;
     8     
     9     private void deal(){
    10         //向list容器中顺序添加指定数量num的整数
    11         if (list==null) {
    12             list = new ArrayList<Integer>();
    13             for (int i = 1; i < 1000; i++) {
    14                 list.add(i);
    15             } 
    16         }                
    17         //打乱list中元素顺序
    18         Collections.shuffle(list);                
    19     }
    20     
    21     //抽奖的方法:抽出指定数量的奖项
    22     public void draw(){
    23         Random rdom = new Random();
    24         
    25         int index = rdom.nextInt(list.size());
    26         System.out.println("一等奖:"+list.get(index));
    27         list.remove(index);
    28         Collections.shuffle(list);
    29         
    30         
    31         for (int i = 0; i < 2; i++) {
    32             int index2 = rdom.nextInt(list.size());
    33             System.out.println("二等奖:"+list .get(index2));
    34             list.remove(index2);            
    35         }
    36         Collections.shuffle(list);
    37         
    38         
    39         for (int i = 0; i < 3; i++) {
    40             int index3 = rdom.nextInt(list.size());
    41             System.out.println("三等奖:"+list .get(index3));
    42             list.remove(index3);
    43         }
    44         Collections.shuffle(list);
    45     }
    46     
    47     
    48     public static void main(String[] args) {
    49         // TODO Auto-generated method stub
    50         raffle rf = new raffle();
    51         rf.deal();
    52         rf.draw();
    53 
    54     }    
    55

     运行结果:

                                                                                                                                             

  • 相关阅读:
    PC版优酷的一次异常
    颜宁开讲啦谈理性思考
    李彦宏开讲啦谈判断能力
    尝试插入cctv视频
    selenium中quit与close方法的区别
    CodeForces 131C The World is a Theatre(组合数)
    CodeForces 446A DZY Loves Sequences(dp)
    UVA 1631 Locker(密码锁)(dp记忆化搜索)
    UVA 1630 Folding(串折叠)(dp记忆化搜索)
    UVA 1629 Cake slicing(切蛋糕)(dp记忆化搜索)
  • 原文地址:https://www.cnblogs.com/Awen-/p/5486166.html
Copyright © 2011-2022 走看看