本文已参与「新人创作礼」活动,一起开启掘金创作之路。
要求如下:
- 定义奖项类Awards,包含成员变量String类型的name(奖项名称)和int类型的count(奖项数量)。
- 定义抽奖类DrawReward,包含成员变量Map<Integer, Awards> 类型的rwdPool(奖池对象)。该类实现功能如下:a) 构造方法中对奖池对象初始化,本实验要求提供不少于4类奖品,每类奖品数量为有限个,每类奖品对应唯一的键值索引(抽奖号)。b) 实现抽奖方法draward,由抽奖号在奖池中抽奖,并根据当前奖池的情况作出对应的逻辑处理;c) 利用迭代器Iterator实现显示奖池奖项情况的方法showPool。
- 编写测试类,实现下图效果:
package com.zhangyufan.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class TestDrawReward {
public static void main(String[] args) {
DrawReward dr = new DrawReward();
for (int i = 0; i < 10; i++) {
int rdKey = (int) (Math.random() * 100);
if (rdKey != 1 && rdKey != 2 && rdKey != 3)
rdKey = 0;
dr.draward(rdKey);
}
dr.showPool();
}
}
class Awards {
private String name;
private int 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;
}
public Awards(String name, int count) {
super();
this.name = name;
this.count = count;
}
public Awards() {
super();
}
}
class DrawReward {
private Map<Integer, Awards> rwdPool = null;
public DrawReward() {
this.rwdPool = new HashMap<Integer, Awards>();
this.rwdPool.put(0, new Awards("阳光普照奖:家庭大礼包", 100));
this.rwdPool.put(1, new Awards("一等奖:华为Mate X", 4));
this.rwdPool.put(2, new Awards("二等奖:格力吸尘器", 6));
this.rwdPool.put(3, new Awards("特等奖:¥5000", 1));
}
public void draward(int rdKey) {
Awards aw = this.rwdPool.get(rdKey);
if (aw == null)
return;
else {
if (aw.getCount() < 1)
System.out.println(aw.getName() + ",该奖项已抽完。");
else {
System.out.println("抽奖结果:" + aw.getName());
aw.setCount(aw.getCount() - 1);
}
}
}
public void showPool() {
Iterator<Awards> it = this.rwdPool.values().iterator();
while (it.hasNext()) {
Awards aw = it.next();
System.out.println(aw.getName() + ";剩余奖项数量:" + aw.getCount());
}
}
}