• 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

     运行结果:

                                                                                                                                             

  • 相关阅读:
    03继承与多态 动手动脑
    data whitening
    特征值和特征向量
    CRC算法
    python 二维字典
    协方差的计算与理解
    Differences between write through and write back
    Differences between page and segment
    虚拟内存和缓存区别
    Python: 统计一个文件中每个单词出现的次数
  • 原文地址:https://www.cnblogs.com/Awen-/p/5486166.html
Copyright © 2020-2023  润新知