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 void setName(String name) { this.name = name; } public void setMoney(int money) { this.money = money; } public String getName() { return name; } public int getMoney() { return money; } }
import java.util.ArrayList; import java.util.Random;public class Number extends User { public Number() { } public Number(String name, int money) { super(name, money); } public void recive(ArrayList<Integer> list) { // 从多个红包当中随机抽取一个给自己 int index = new Random().nextInt(list.size()); // 根据索引,从集合当中删除。并且得到被删除的红包给我自己 int delta= list.remove(index); //当前成员自自己有多少钱 int money = super.getMoney(); //加法,并且重新设置回去 super.setMoney(money+delta); } }
public class Maneger extends User { public Maneger(){ } public Maneger(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 (totalmoney > leftmoney){ System.out.println("金额不足"); return redList; } // 扣钱,其实就是重新设置余额 super.setMoney(leftmoney-totalmoney); // 发红包需要拆分成count份 int avg=totalmoney / count; int mod =totalmoney % count;//也就是说余下的零头 // 剩下的零头,抱在最后一个红包当中 // 下面把红包放在集合当中 for (int i = 0; i < count-1; i++) { redList.add(avg); } int last=avg+mod; redList.add(last); return redList; } }
public class MainRedPacket { public static void main(String[] args) { Maneger maneger= new Maneger("群主",100); Number one = new Number("成员A",0); Number two = new Number("成员A",0); Number three = new Number("成员A",0); maneger.show(); one.show(); two.show(); three.show(); System.out.println("============"); //群主发20 分3个红包 ArrayList<Integer> redList =maneger.send(20,3); // 三个成员去收红包 one.recive(redList); two.recive(redList); three.recive(redList); maneger.show(); one.show(); two.show(); three.show(); } }
原文地址:https://www.cnblogs.com/xinglingzhiren/p/10991989.html
时间: 2024-10-08 13:59:04