群主发普通红包
群主发普通红包。某群有多名成员,群主给成员发普通红包。普通红包的规则:
1. 群主的一笔金额,从群主余额中扣除,平均分成n等份,让成员领取。
2. 成员领取红包后,保存到成员余额中。
请根据描述,完成案例中所有类的定义以及指定类之间的继承关系,并完成发红包的操作。
1 public class User { 2 3 private String name ; //姓名 4 private int money ; //金额 5 6 public User() { 7 } 8 9 public User(String name, int money) { 10 this.name = name; 11 this.money = money; 12 } 13 // 展示当前用户有多少钱 14 public void show(){ 15 System.out.println("姓名:" + name +" 余额:" + money); 16 } 17 public String getName() { 18 return name; 19 } 20 21 public void setName(String name) { 22 this.name = name; 23 } 24 25 public int getMoney() { 26 return money; 27 }
1 import java.util.ArrayList; 2 3 public class Manager extends User{ 4 5 public Manager(){ 6 //super();默认赠送 7 } 8 9 public Manager(String name, int money) { 10 super(name, money); 11 } 12 13 14 public ArrayList<Integer> send(int totalMoney, int count){ 15 16 ArrayList<Integer> redList = new ArrayList<>(); 17 //首先看一下,群主有多少钱 18 //int leftMoney = super.money; 错误写法 19 int leftMoney = super.getMoney(); 20 if(leftMoney < totalMoney){ 21 System.out.println("余额不足"); 22 return redList; //返回空集合 23 } 24 //扣钱,其实就是重新设置余额 25 super.setMoney(leftMoney - totalMoney); 26 27 //发红包,平均发成count份 28 int avg = totalMoney / count; 29 int mod = totalMoney % count; 30 31 //除不开的零头放在最后一个红包中 32 //下面吧红包放在集合中 33 for (int i = 0; i < count-1; i++) { 34 redList.add(avg); 35 } 36 //最后一个红包 37 int last = avg + mod; 38 redList.add(last); 39 40 return redList; 41 } 42 }
1 import java.util.ArrayList; 2 import java.util.Random; 3 4 public class Member extends User{ 5 6 public Member() { 7 } 8 9 public Member(String name, int money) { 10 super(name, money); 11 } 12 13 public void receive(ArrayList<Integer> list){ 14 //从众多红包中抽取一个给自己 15 //随机获取一个集合当中的索引编号 16 int index = new Random().nextInt(list.size()); 17 //根据索引从集合中删除,并把删除的红包给自己 18 int delta = list.remove(index); 19 20 //当前成员自己有多少钱 21 int money = super.getMoney(); 22 //领了红包后多少钱 23 super.setMoney(money + delta); 24 } 25 }
1 import java.util.ArrayList; 2 3 public class MainRedPacket { 4 5 public static void main(String[] args) { 6 Manager manager = new Manager("群主", 200); 7 8 Member one = new Member("成员A", 0); 9 Member two = new Member("成员B", 0); 10 Member three = new Member("成员C", 0); 11 Member four = new Member("成员D", 0); 12 Member five = new Member("成员E", 0); 13 Member six = new Member("成员F", 0); 14 15 manager.show(); 16 one.show(); 17 two.show(); 18 three.show(); 19 four.show(); 20 five.show(); 21 six.show(); 22 System.out.println("=========="); 23 24 25 //群主开始发红包 26 ArrayList<Integer> redList = manager.send(168, 6); 27 one.receive(redList); 28 two.receive(redList); 29 three.receive(redList); 30 four.receive(redList); 31 five.receive(redList); 32 six.receive(redList); 33 34 //领完红包后,各自金额多少 35 manager.show(); 36 one.show(); 37 two.show(); 38 three.show(); 39 four.show(); 40 five.show(); 41 six.show(); 42 System.out.println("=========="); 43 } 44 45 }