Java消费抽奖功能
阿炳的旅程 人气:0要求如下:
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(); } }
加载全部内容