JAVA 實現簡單的發紅包案例
阿新 • • 發佈:2019-05-11
png image bsp move span 展示 member img 代碼
1 package Demo511;
2
3 import java.util.ArrayList;
4
5 public class DemoSend {
6 public static void main(String[] args) {
7 Manager manager =new Manager("群主",1000);
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
14 ArrayList<Integer> redlist =manager.send(666,5);
15
16 one.receive(redlist);
17 two.receive(redlist);
18 three.receive(redlist);
19 four.receive(redlist);
20 five.receive(redlist);
21
22 manager.show();
23 one.show();
24 two.show();
25 three.show();
26 four.show();
27 five.show();
28 }
29 }
??是成員類,群主繼承成員,群員繼承成員
1 package Demo511;
2
3 public class User {
4 private String name ;
5 private int money;
6
7 public User(){
8
9 }
10
11 public User(String name,int money) {
12 this.money=money;
13 this.name = name;
14 }
15 //展示一下,當前用戶的錢
16 public void show(){
17 System.out.println("我叫:"+name+",還有"+money+"塊錢");
18 }
19 public String getName(){
20 return name;
21 }
22 public void setName(String name){
23 this.name=name;
24 }
25 public int getMoney(){
26 return money;
27 }
28 public void setMoney(int money){
29 this.money=money;
30 }
31 }
1 package Demo511;
2
3 import java.util.ArrayList;
4 /*
5 默認構造,有參構造
6 */
7 public class Manager extends User{
8 public Manager(){
9 }
10 public Manager(String name, int money) {
11 super(name, money);
12 }
13 public ArrayList<Integer> send(int totalMoney,int count) {
14 //用一個集合,來存儲若幹個紅包的金額
15 ArrayList<Integer> redList = new ArrayList<>();
16 //查看群主的金錢余額
17 int leftMoney =super.getMoney();//群主當前余額
18 if (totalMoney>leftMoney){
19 System.out.println("余額不足");
20 return redList; //返回空集合
21 }
22 //扣錢就是重新設置余額
23 super.setMoney(leftMoney-totalMoney);
24 //發紅包需要評分count份
25 int avg =totalMoney/count;
26 int mod =totalMoney%count;
27 //除不開的金錢,放到最後一個紅包裏面
28 for (int i = 0; i < count-1; i++) {
29 redList.add(avg);
30 }
31 redList.add(avg+mod);
32 return redList;
33 }
34 }
1 package Demo511;
2
3 import java.util.ArrayList;
4 import java.util.Random;
5
6 public class Member extends User {
7 public Member() {
8 }
9 public Member(String name, int money) {
10 super(name, money);
11 }
12 public void receive(ArrayList<Integer>list){
13 //從多個紅包當中抽取一個給我。
14 //隨機獲取一個集合的索引編號。
15 int index =new Random().nextInt(list.size());
16 //刪除一個隨機紅包,並且給我。
17 int detal = list.remove(index);
18 int money = super.getMoney();
19 super.setMoney(money+detal);
20 }
21 }
代碼運行??
JAVA 實現簡單的發紅包案例