最大的父类(user)
package Demo11;
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("我叫:"+ name+ "、" + "我有多少钱" + money);
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
private int money;//当前用户有的钱数
public User() {
}
public User(String name, int money) {
this.name = name;
this.money = money;
}
}
收红包的成员(Member)
package Demo11;
import java.util.ArrayList;
import java.util.Random;
public class Member extends User{
public Member(String name, int money) {
super(name, money);
}
public Member() {
}
public void receive(ArrayList<Integer> list){
//从多个红包当中,随机抽取一个
int index = new Random().nextInt(list.size());
//根据索引,从集合当中删除,并且得到被删除的
int delta = list.remove(index);
//
int money = super.getMoney();
money += delta;
super.setMoney(money);
}
}
发红包的群主
package Demo11;
import java.util.ArrayList;
//群主的类
public class Manger extends User{
public Manger(){
}
public Manger(String name, int money) {
super(name, money);
}
public ArrayList<Integer> send(int totalMoney,int count){
//需要一个集合,用来存储若干个红包的金额
ArrayList<Integer> redList = new ArrayList<>();
//首先看一下群主有多少钱]
int leftMoney = super.getMoney();
if(leftMoney < totalMoney){
System.out.println("余额不足");
return redList;
}
else{
super.setMoney(leftMoney - totalMoney);
}
//发红包需要平均拆成count份
int avg = totalMoney/count;
int mod = totalMoney%count;//余数也就是甩下的零头
//剩下的零钱包在最后一个红包里面
//下面把红包一个个放在集合当中
for (int i = 0; i < count-1; i++) {
redList.add(avg);
}
redList.add(avg+mod);
return redList;
}
}
主方法:
package Demo11;
import java.util.ArrayList;
public class mainRed {
public static void main(String[] args) {
Manger manger = new Manger("群主",100);
Member one = new Member("成员A",0);
Member two = new Member("成员B",0);
Member three = new Member("成员C",0);
Member four = new Member("成员D",0);
manger.show();
one.show();
two.show();
three.show();
four.show();
System.out.println("===============================");
ArrayList<Integer> redList = manger.send(21,4);
//三个成员收红包
one.receive(redList);
two.receive(redList);
three.receive(redList);
four.receive(redList);
manger.show();
one.show();
two.show();
three.show();
four.show();
}
}
运行结果截图: