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

     运行结果:

                                                                                                                                             

  • 相关阅读:
    计算几何 判断点在直线的左右哪一侧
    图论 迪杰斯特拉dijkstra求最短路径
    图论 用prim法求最小生成树
    图论 邻接表广搜
    图论 用广搜搜邻接矩阵
    图论 邻接表建图+dfs
    图论 邻接矩阵建图+dfs遍历
    HDU 2141 二分查找
    二叉树知道前序和中序求后序,知道中序后序求中序
    二叉树的查找
  • 原文地址:https://www.cnblogs.com/Awen-/p/5486166.html
Copyright © 2011-2022 走看看