java编程:群主发红包 群主发普通红包。某群有多名成员,群主给成员发普通红包。 普通红包的规则: (1)群主的一笔金额,从群主余额中扣除,分成口份,让成员领取随机金额(假设随机金额在0.01 与剩余平均值*2之间)。 (2) 成员领取红包后,存储到成员的余额中。 请根据上述描述,完成案例中所有类的定义以及指定类之间的继示关系,并完成发红色、领红包的採作。
时间: 2024-02-15 10:02:30 浏览: 49
根据上述描述,我们可以定义以下类:
1. 群主(GroupOwner)类
2. 群成员(GroupMember)类
3. 红包(RedPacket)类
4. 普通红包(NormalRedPacket)类
5. 余额(Balance)类
其中,群主类和群成员类是继承自余额类的,因为它们都需要有余额属性和相关的余额操作方法。
类之间的继承关系如下:
```
Balance
|
|
/ \
/ \
GroupOwner GroupMember
```
RedPacket类是普通红包类的父类,因为后续可能会有其他类型的红包。
类之间的继承关系如下:
```
RedPacket
|
|
NormalRedPacket
```
下面是相应类的定义和发红包、领红包的操作:
```java
import java.util.*;
class Balance {
private double amount;
public Balance(double amount) {
this.amount = amount;
}
public double getAmount() {
return amount;
}
public void add(double amount) {
this.amount += amount;
}
public void subtract(double amount) {
this.amount -= amount;
}
}
class GroupOwner extends Balance {
public GroupOwner(double amount) {
super(amount);
}
public NormalRedPacket sendRedPacket(int numMembers) {
double totalAmount = getAmount();
NormalRedPacket redPacket = new NormalRedPacket(totalAmount, numMembers);
subtract(totalAmount);
return redPacket;
}
}
class GroupMember extends Balance {
public GroupMember(double amount) {
super(amount);
}
public void receiveRedPacket(RedPacket redPacket) {
double amount = redPacket.draw();
add(amount);
}
}
class RedPacket {
protected double totalAmount;
protected int numMembers;
public RedPacket(double totalAmount, int numMembers) {
this.totalAmount = totalAmount;
this.numMembers = numMembers;
}
public double draw() {
return 0;
}
}
class NormalRedPacket extends RedPacket {
private double averageAmount;
private List<Double> amounts;
public NormalRedPacket(double totalAmount, int numMembers) {
super(totalAmount, numMembers);
this.averageAmount = totalAmount / numMembers;
this.amounts = new ArrayList<>();
// 随机生成每个成员的红包金额
for (int i = 0; i < numMembers; i++) {
double amount;
if (i == numMembers - 1) {
// 最后一个成员获得剩余的金额
amount = totalAmount - getAmountsSum();
} else {
// 其他成员获得随机金额
amount = Math.random() * (averageAmount * 2 - 0.01) + 0.01;
}
amounts.add(amount);
}
}
public double draw() {
// 随机选择一个红包金额
int idx = (int) (Math.random() * amounts.size());
double amount = amounts.get(idx);
amounts.remove(idx);
return amount;
}
private double getAmountsSum() {
double sum = 0;
for (double amount : amounts) {
sum += amount;
}
return sum;
}
}
public class Main {
public static void main(String[] args) {
// 发红包
GroupOwner groupOwner = new GroupOwner(1000);
NormalRedPacket redPacket = groupOwner.sendRedPacket(10);
// 领红包
List<GroupMember> members = new ArrayList<>();
for (int i = 0; i < 10; i++) {
GroupMember member = new GroupMember(0);
member.receiveRedPacket(redPacket);
members.add(member);
}
// 打印每个成员的余额
for (int i = 0; i < members.size(); i++) {
System.out.printf("Member %d balance: %.2f\n", i + 1, members.get(i).getAmount());
}
}
}
```
注意,以上代码只是一个简单的实现示例,实际应用中可能需要更加严谨的设计和处理。
阅读全文