Java使用HashMap映射實現消費抽獎功能
本文實例為大家分享了Java實現消費抽獎功能的具體代碼,供大家參考,具體內容如下
要求如下:
1、定義獎項類Awards,包含成員變量String類型的name(獎項名稱)和int類型的count(獎項數量)。
2、定義抽獎類DrawReward,包含成員變量Map<Integer, Awards> 類型的rwdPool(獎池對象)。該類實現功能如下:a) 構造方法中對獎池對象初始化,本實驗要求提供不少于4類獎品,每類獎品數量為有限個,每類獎品對應唯一的鍵值索引(抽獎號)。b) 實現抽獎方法draward,由抽獎號在獎池中抽獎,并根據當前獎池的情況作出對應的邏輯處理;c) 利用迭代器Iterator實現顯示獎池獎項情況的方法showPool。
3、編寫測試類,實現下圖效果:

實現代碼:
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("抽獎結果:"+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()+";剩余獎項數量:"+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();
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Java?String源碼contains題解重復疊加字符串匹配
這篇文章主要為大家介紹了Java?String源碼contains題解重復疊加字符串匹配示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11

