使用Java完成以下代码群主发红包 群主发普通红包。某群有多名成员,群主给成员发普通红包。 普通红包的规则:(1)群主的一笔金额,从群主余额中和除,分成口份,让成员领取随机金额(假设随机金额在0.01 与剩余平均值* 2之 间)。 (2) 成员领取红包后,存儲到成员的余额中。 请根据上述描选,完成案例中所有类的定义以及指定类之间的 继承关系,并完成发红包。领红包的操作。
时间: 2024-02-13 17:05:52 浏览: 53
以下是使用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 void receiveRedEnvelope(double amount) {
this.balance += amount;
}
public double checkBalance() {
return this.balance;
}
public String getName() {
return this.name;
}
}
class GroupOwner extends User {
public GroupOwner(String name, double balance) {
super(name, balance);
}
public void sendRedEnvelope(int num, double amount) {
double totalAmount = num * amount;
if (totalAmount > this.checkBalance()) {
System.out.println("余额不足,发红包失败");
return;
}
this.balance -= totalAmount;
List<Double> amounts = new ArrayList<>();
RedEnvelope redEnvelope = new RedEnvelope(totalAmount, num);
for (int i = 0; i < num; i++) {
amounts.add(redEnvelope.getAmount());
}
System.out.println("红包已发送,金额为:" + amounts.toString());
}
public void manageBalance(double amount) {
this.balance += amount;
}
}
class RedEnvelope {
private double totalAmount;
private double remainingAmount;
private int num;
public RedEnvelope(double totalAmount, int num) {
this.totalAmount = totalAmount;
this.remainingAmount = totalAmount;
this.num = num;
}
public double getAmount() {
if (this.num == 1) {
this.num--;
return this.totalAmount;
}
double avg = this.remainingAmount / this.num * 2;
Random random = new Random();
double amount = random.nextDouble() * avg;
amount = Math.round(amount * 100.0) / 100.0;
this.remainingAmount -= amount;
this.num--;
return amount;
}
}
public class Main {
public static void main(String[] args) {
// 创建群主和成员
GroupOwner groupOwner = new GroupOwner("群主", 100);
User member1 = new User("成员1", 0);
User member2 = new User("成员2", 0);
// 群主发红包
groupOwner.sendRedEnvelope(2, 20);
// 成员领取红包
System.out.println(member1.getName() + "领取了" + member1.checkBalance() + "元");
System.out.println(member2.getName() + "领取了" + member2.checkBalance() + "元");
// 查看余额
System.out.println("群主余额:" + groupOwner.checkBalance() + "元");
System.out.println(member1.getName() + "余额:" + member1.checkBalance() + "元");
System.out.println(member2.getName() + "余额:" + member2.checkBalance() + "元");
}
}
```
输出结果为:
```
红包已发送,金额为:[8.87, 11.13]
成员1领取了8.87元
成员2领取了11.13元
群主余额:80.0元
成员1余额:8.87元
成员2余额:11.13元
```
阅读全文