package cn.learn.chouxiang.practice03; public class Users { private String name; //姓名 private double money; //余额 public void show(){ System.out.println(String.format("我的名字是:%s,我还剩:%.2f ",this.name,this.money)); } public Users() { } public Users(String name, double money) { this.name = name; this.money = money; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } }
package cn.learn.chouxiang.practice03; import java.util.ArrayList; import java.util.Random; public class Manager extends Users { public Manager() { } public Manager(String name, double money) { super(name, money); //如果主程序new 出来,则子类含父类,与另一个继承会独立开来 } public ArrayList<Double> send(int totalMoney, int count){ //首先用集合存储若干个红包金额 ArrayList<Double> readList=new ArrayList<>(); //首先要看群主的余额 double lefMoney = super.getMoney(); //群主的前 if(totalMoney > lefMoney){ System.out.println("没钱啦"); return readList; } //扣钱 else{ super.setMoney(lefMoney-totalMoney); double leftSum=totalMoney; for (int i = 0; i < count ; i++) { double avg=(double)leftSum / (new Random(3).nextDouble()+2.4); leftSum -=avg; //把红包放入集合 readList.add(avg); //最后一个红包单独处理 if(i == count-1) readList.add(leftSum); } System.out.println("红包:"+readList+"共计:"+readList.stream().mapToDouble(Double::doubleValue).sum()); return readList; } } }
package cn.learn.chouxiang.practice03; import java.util.ArrayList; import java.util.Random; public class Member extends Users { public Member() { } public Member(String name, double money) { super(name, money); } //收红包 public void recieve(ArrayList<Double> list){ //从集合随机抽取一个放入红包 //首先得到红包索引值 int index = new Random().nextInt(list.size()); //删除这个索引值的红包,并把钱存入余额 double money=list.remove(index); super.setMoney(money+super.getMoney()); } }
package cn.learn.chouxiang.practice03; import java.util.ArrayList; public class Enter { public static void main(String[] args) { Manager qunzhu=new Manager("群主",55.0); Member qunyuan1=new Member("群员A",0.0); Member qunyuan2=new Member("群员B",0.0); Member qunyuan3=new Member("群员C",0.0); Member qunyuan4=new Member("群员D",0.0); Member qunyuan5=new Member("群员E",0.0); Member qunyuan6=new Member("群员F",0.0); //发红包 ArrayList<Double> list=qunzhu.send(30,6); //收红包 qunyuan1.recieve(list); qunyuan2.recieve(list); qunyuan3.recieve(list); qunyuan4.recieve(list); qunyuan5.recieve(list); qunyuan6.recieve(list); qunzhu.show(); qunyuan1.show(); qunyuan2.show(); qunyuan3.show(); qunyuan4.show(); qunyuan5.show(); qunyuan6.show(); } }
//总结:格式化输出,熟悉随机数的生成,ArrayList的运用