本文實(shí)例為大家分享了Java實(shí)現(xiàn)消費(fèi)抽獎功能的具體代碼,供大家參考,具體內(nèi)容如下
要求如下:
1、定義獎項(xiàng)類Awards,包含成員變量String類型的name(獎項(xiàng)名稱)和int類型的count(獎項(xiàng)數(shù)量)。
2、定義抽獎類DrawReward,包含成員變量Map<Integer, Awards> 類型的rwdPool(獎池對象)。該類實(shí)現(xiàn)功能如下:a) 構(gòu)造方法中對獎池對象初始化,本實(shí)驗(yàn)要求提供不少于4類獎品,每類獎品數(shù)量為有限個(gè),每類獎品對應(yīng)唯一的鍵值索引(抽獎號)。b) 實(shí)現(xiàn)抽獎方法draward,由抽獎號在獎池中抽獎,并根據(jù)當(dāng)前獎池的情況作出對應(yīng)的邏輯處理;c) 利用迭代器Iterator實(shí)現(xiàn)顯示獎池獎項(xiàng)情況的方法showPool。
3、編寫測試類,實(shí)現(xiàn)下圖效果:
實(shí)現(xiàn)代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
import java.util.Random; import java.util.HashMap; import java.util.Iterator; import java.util.Map; class Awards { private String name; private int count; public Awards() { } public Awards(String name, int count) { this .name = name; this .count = count; } public String getName() { return name; } public void setName(String name) { this .name = name; } public int getCount() { return count; } public void setCount( int count) { this .count = count; } } class DrawReward { private Map<Integer,Awards> rwdPool= null ; public DrawReward(){ this .rwdPool= new HashMap<Integer,Awards>(); rwdPool.put( 0 , new Awards( "陽光普照獎:家庭大禮包" , 100 )); rwdPool.put( 1 , new Awards( "一等獎:華為Mate X" , 4 )); rwdPool.put( 2 , new Awards( "二等獎:格力吸塵器" , 6 )); rwdPool.put( 3 , new Awards( "特等獎:¥5000" , 1 )); } public boolean hasAward( int rdkey){ Awards awards = this .rwdPool.get(rdkey); if (awards.getCount()== 0 ) return false ; else return true ; } public void draward( int rdKey) { Awards aw = this .rwdPool.get(rdKey); System.out.println( "抽獎結(jié)果:" +aw.getName()); aw.setCount(aw.getCount()- 1 ); } public void showPool(){ Iterator<Awards> it; it = rwdPool.values().iterator(); while (it.hasNext()){ Awards aw = it.next(); System.out.println(aw.getName()+ ";剩余獎項(xiàng)數(shù)量:" +aw.getCount()); } } } public class MainClass { public static void main(String[] args) { DrawReward draw = new DrawReward(); for ( int i= 0 ;i< 10 ;i++){ Random rd = new Random(); int rdKey = rd.nextInt( 4 ); if (draw.hasAward(rdKey)) { draw.draward(rdKey); } else { i--; } } draw.showPool(); } } |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/weixin_51119270/article/details/120316337