java编程:群主发红包 群主发普通红包。某群有多名成员,群主给成员发普通红包。 普通红包的规则: (1)群主的一笔金额,从群主余额中扣除,分成口份,让成员领取随机金额(假设随机金额在0.01 与剩余平均值*2之间)。 (2) 成员领取红包后,存储到成员的余额中。 请根据上述描述,完成案例中所有类的定义以及指定类之间的继示关系,并完成发红色、领红包的採作。
时间: 2024-02-15 19:02:46 浏览: 74
Java基础之发红包案例
以下是可能的Java代码实现,实现了群主发普通红包的功能:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class User {
private String name;
private double balance;
public User(String name, double balance) {
this.name = name;
this.balance = balance;
}
public String getName() {
return name;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void receive(double amount) {
balance += amount;
}
public void send(User receiver, double amount) {
if (balance >= amount) {
balance -= amount;
receiver.receive(amount);
System.out.println(name + " sent " + amount + " to " + receiver.getName());
} else {
System.out.println(name + " does not have sufficient balance.");
}
}
}
class Group {
private User owner;
private List<User> members;
private double balance;
public Group(User owner) {
this.owner = owner;
this.members = new ArrayList<>();
this.balance = 0.0;
}
public void addMember(User member) {
members.add(member);
}
public void sendNormalRedPacket(int numPackets) {
if (owner.getBalance() < numPackets) {
System.out.println("Owner does not have sufficient balance.");
return;
}
double avgAmount = balance / numPackets;
Random random = new Random();
for (User member : members) {
double amount = random.nextDouble() * avgAmount * 2;
if (amount < 0.01 || amount > avgAmount * 2) {
amount = avgAmount;
}
owner.send(member, amount);
balance -= amount;
}
}
public void deposit(double amount) {
balance += amount;
owner.setBalance(owner.getBalance() - amount);
}
}
public class RedPacketDemo {
public static void main(String[] args) {
User owner = new User("Owner", 100.0);
Group group = new Group(owner);
User member1 = new User("Member1", 0.0);
User member2 = new User("Member2", 0.0);
group.addMember(member1);
group.addMember(member2);
group.deposit(10.0);
group.sendNormalRedPacket(5);
System.out.println("Owner balance: " + owner.getBalance());
System.out.println("Member1 balance: " + member1.getBalance());
System.out.println("Member2 balance: " + member2.getBalance());
}
}
```
在这个实现中,User类表示一个用户,包括用户的姓名和余额,以及发送和接收金额的方法。
Group类表示一个群组,包括群主、成员列表和余额。群主可以添加成员、充值余额和发普通红包。发普通红包时,群主的余额会减去红包总金额,然后按照红包数量计算平均值和随机金额,随机金额在0.01和平均值的两倍之间。每个成员收到红包后,会将金额存储到自己的余额中。
RedPacketDemo类是一个示例程序,创建了一个群组并执行了一些操作,包括添加成员、充值余额和发普通红包。输出显示了每个用户的余额。
阅读全文