package cn.learn.chouxiang.practice03; public class Users { private String name; //姓名 private double money; //餘額 public void show(){ System.out.println(String.format("個人名字是:%s,我還剩:%.2f\n",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的運用java