Java使用HashMap映射實(shí)現(xiàn)消費(fèi)抽獎(jiǎng)功能
本文實(shí)例為大家分享了Java實(shí)現(xiàn)消費(fèi)抽獎(jiǎng)功能的具體代碼,供大家參考,具體內(nèi)容如下
要求如下:
1、定義獎(jiǎng)項(xiàng)類Awards,包含成員變量String類型的name(獎(jiǎng)項(xiàng)名稱)和int類型的count(獎(jiǎng)項(xiàng)數(shù)量)。
2、定義抽獎(jiǎng)?lì)怐rawReward,包含成員變量Map<Integer, Awards> 類型的rwdPool(獎(jiǎng)池對象)。該類實(shí)現(xiàn)功能如下:a) 構(gòu)造方法中對獎(jiǎng)池對象初始化,本實(shí)驗(yàn)要求提供不少于4類獎(jiǎng)品,每類獎(jiǎng)品數(shù)量為有限個(gè),每類獎(jiǎng)品對應(yīng)唯一的鍵值索引(抽獎(jiǎng)號)。b) 實(shí)現(xiàn)抽獎(jiǎng)方法draward,由抽獎(jiǎng)號在獎(jiǎng)池中抽獎(jiǎng),并根據(jù)當(dāng)前獎(jiǎng)池的情況作出對應(yīng)的邏輯處理;c) 利用迭代器Iterator實(shí)現(xiàn)顯示獎(jiǎng)池獎(jiǎng)項(xiàng)情況的方法showPool。
3、編寫測試類,實(shí)現(xiàn)下圖效果:
實(shí)現(xiàn)代碼:
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("陽光普照獎(jiǎng):家庭大禮包",100)); rwdPool.put(1,new Awards("一等獎(jiǎng):華為Mate X",4)); rwdPool.put(2,new Awards("二等獎(jiǎng):格力吸塵器",6)); rwdPool.put(3,new Awards("特等獎(jiǎng):¥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ǎng)結(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()+";剩余獎(jiǎng)項(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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java?String源碼contains題解重復(fù)疊加字符串匹配
這篇文章主要為大家介紹了Java?String源碼contains題解重復(fù)疊加字符串匹配示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11老生常談設(shè)計(jì)模式之動(dòng)態(tài)代理
下面小編就為大家?guī)硪黄仙U勗O(shè)計(jì)模式之動(dòng)態(tài)代理。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06