java實現一個簡單的抽獎功能


基本思路

    1、確定你要的獎項,比如:一等獎、二等獎、三等獎、謝謝惠顧;

    2、設置4個區間,0~5是一等獎、6~15是二等獎、16~40是三等獎、剩下的40~100是謝謝惠顧;

    3、產生一個隨機數,判斷隨機數在哪個區間之內,就會獲得相應的獎項;

很簡單的一個方法,剛好正在做的微信小程序這邊有積分抽獎這個功能,就先寫一個玩一玩,下面貼代碼,因為很簡單,所以后面我就不多逼逼了,大家自己看,如果有錯誤,歡迎指正!!

    

 1 public JsonResult luckyDraw() {
 2         JsonResult jsonResult=new JsonResult("200");
 3         jsonResult.setFlag(true);
 4         jsonResult.setMsg("抽獎成功");
 5         
 6         //定義中獎率分母百分之
 7         int  probabilityCount=100;
 8         
 9         //最小概率
10         String min="min";
11         
12         //最大概率
13         String max="max";
14         Integer tempInt=0;
15         
16         //待中將商品數組
17         Map<String,Map<String,Integer>> prizeMap=new HashMap<>();
18             
19         //獲取商品列表
20         List<Prize> prizeList=prizeDao.findAll();
21         
22         for(Prize prize:prizeList) {
23             Map<String, Integer> oddMap=new HashMap<>();
24             //最小概率值
25             oddMap.put(min, tempInt);
26             tempInt=tempInt+prize.getPrizeOdd();
27             //最大概率
28             oddMap.put(max, tempInt);
29             prizeMap.put(prize.getId(), oddMap);//(獎品id,最小概率~最大概率)
30         }
31         
32         //隨機一個數字
33         int index=(int) (Math.random()* probabilityCount);
34         Prize prize=null;//中獎商品容器
35         Set<String> prizeIds=prizeMap.keySet();//拿到所有獎品id
36         for(String prizesId:prizeIds) {
37             Map<String, Integer> oddMap=prizeMap.get(prizesId);//商品的概率
38             Integer minNum=oddMap.get(min);
39             Integer maxNum=oddMap.get(max);
40             
41             //校驗index在那個商品概率中間
42             if(minNum <=index && maxNum > index) {
43                 prize=prizeDao.getOne(prizesId);
44                 break;
45             }
46         }
47         
48         if(prize == null) {
49             prize=null;
50         }
51         
52         jsonResult.setObj(prize.getPrizeName());
53         return jsonResult;
54     }

測試結果如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM