需求
群主发普通红包,群里有多名成员,群主给成员发普通红包,普通红包的规则:
- 群主的一笔金额,从群主余额中扣除,平均分成n等份,让成员领取
- 成员领取红包后,保存到成员余额中
根据描述,完成案例中所有类的定义以及指定类之间的继承关系,并完成发红包的操作。
概要设计
用户类 User:
姓名
余额
展示信息
群主类 Manager:
发红包
0. 发红包的金额要小于余额
1. 存储红包的数组
2. 发的红包要分成n等份
3. 群主余额扣减
4. 返回红包数组
普通成员类 Member:
收红包
1. 接收一个红包数组
2. 成员根据数组的索引领取红包
随机获取数组中的索引,然后将索引对应的金额从数组中移除,给到自己账户
3. 成员的余额增加
示例代码
User.java
package redEnvelope;
public class User {
private String name;
private int money;
public User() {
}
public User(String name, int money) {
this.name = name;
this.money = money;
}
public void show(){
System.out.println("我叫:" + name + ",余额:" + money);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
Manager.java
package redEnvelope;
import java.util.ArrayList;
public class Manager extends User{
public Manager(){
//这里留空,编译器会默认给加一个super();
}
public Manager(String name, int money) {
super(name, money);
}
public ArrayList<Integer> send(int money, int count) {
int balance = super.getMoney();
//1. 存储红包的数组
ArrayList<Integer> redList = new ArrayList<>();
//0. 异常检测
if(money > balance){
System.out.println("余额不足");
return redList;
}
//2. 发的红包要分成n等份
int avg = money / count;
int mod = money % count;
for (int i = 0; i < count-1; i++) {
redList.add(avg);
}
int last = avg + mod;
redList.add(last);
System.out.println("红包数组:" + redList);
//3. 群主余额扣减
super.setMoney(balance - money);
//4. 返回红包数组
return redList;
}
}
Member.java
package redEnvelope;
import java.util.ArrayList;
import java.util.Random;
public class Member extends User {
public Member(){
}
public Member(String name, int money) {
super(name, money);
}
public void receive(ArrayList<Integer> list){
Random r = new Random();
int index = r.nextInt(list.size());
int delta = list.remove(index);
int money= super.getMoney();
super.setMoney(money + delta);
}
}
DemoMain.java
package redEnvelope;
import java.util.ArrayList;
public class DemoMain {
public static void main(String[] args) {
Manager manager = new Manager("唐三藏",100);
Member a = new Member("孙悟空", 1);
Member b = new Member("猪八戒", 2);
Member c = new Member("沙悟净", 3);
Member d = new Member("孙悟空", 0);
Member e = new Member("猪八戒", 0);
Member f = new Member("沙悟净", 0);
System.out.println("当前群主及成员的余额:");
manager.show();
a.show();
b.show();
c.show();
d.show();
e.show();
f.show();
ArrayList redList = manager.send(34,6);
a.receive(redList);
b.receive(redList);
c.receive(redList);
d.receive(redList);
e.receive(redList);
f.receive(redList);
System.out.println("抢完红包后,群主及成员的余额:");
manager.show();
a.show();
b.show();
c.show();
d.show();
e.show();
f.show();
}
}
当前群主及成员的余额:
我叫:唐三藏,余额:100
我叫:孙悟空,余额:1
我叫:猪八戒,余额:2
我叫:沙悟净,余额:3
我叫:孙悟空,余额:0
我叫:猪八戒,余额:0
我叫:沙悟净,余额:0
红包数组:[5, 5, 5, 5, 5, 9]
抢完红包后,群主及成员的余额:
我叫:唐三藏,余额:66
我叫:孙悟空,余额:6
我叫:猪八戒,余额:7
我叫:沙悟净,余额:8
我叫:孙悟空,余额:5
我叫:猪八戒,余额:9
我叫:沙悟净,余额:5