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

 運行結果:

                                                                                                                                         

 


免責聲明!

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



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