题目描述:
分析:
代码实现:
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 String getName() { return name; } public void setName(String name) { this.name = name; } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } }
//群主的类 public class Manager extends User { public Manager() { } public Manager(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 Member extends User { public Member() { } public Member(String name, int money) { super(name, money); } public void receive(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 MainRed { public static void main(String[] args) { Manager manager=new Manager("群主",100); Member one=new Member("成员A",0); Member two=new Member("成员B",0); Member three=new Member("成员C",0); manager.show(); one.show(); two.show(); three.show(); System.out.println("======="); //群主总共发20,分成3个红包 ArrayList<Integer> redList=manager.send(20,3); //三个普通成员收红包 one.receive(redList); two.receive(redList); three.receive(redList); manager.show(); one.show(); two.show(); three.show(); } }