模拟发红包案例-Java

模拟发红包

  • 结构分析

代码

  • User类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class User {
private String name;
private double money;

public User() {
}

public User(String name, double money) {
this.name = name;
this.money = money;
}

//显示信息
public void show() {
System.out.println("我叫:" + this.name + "剩余金额:" + this.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;
}
}

  • Manager类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class Manager extends User {
public Manager() {
}

public Manager(String name, int money) {
super(name, money);
}

//发平均红包
public ArrayList<Double> send(double totoalMoney, int count) {
/**红包金额平等
//存放若干红包金额
ArrayList<Integer> integerArrayList = new ArrayList<>();
if (totoalMoney > super.getMoney()) {
System.out.println("余额不足!");
return integerArrayList;
}
int avg = totoalMoney / count;//均分
int mod = totoalMoney % count;//余数
//修改余额
super.setMoney(super.getMoney() - totoalMoney);
for (int i = 0; i < count - 1; i++) {
integerArrayList.add(avg);
}
//最后一个人分红包
int last = mod + avg;
integerArrayList.add(last);
return integerArrayList;
**/

//随机分配金额,最少一分钱。最多不超过剩下金额平均值的2倍
//公式:0.01 + random.nextInt(leftMoney /leftCount * 2)

Random r = new Random();
//totoalMoney最多两位小数,计算完强转为int
int leftMoney = (int) (totoalMoney* 100);//转换成分计算

int leftCount = count;
int max = leftMoney / leftCount * 2;
ArrayList<Double> list = new ArrayList<>();
//随机发前count-1个
for (int i = 0; i < count - 1; i++) {
int money = r.nextInt(leftMoney / leftCount * 2) + 1;
list.add((double) money / 100);
leftMoney -= money;
leftCount--;
}
list.add((double) leftMoney / 100);
super.setMoney(super.getMoney()-totoalMoney);
return list;
}

}

  • Member类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Member extends User {
public Member() {
}

public Member(String name, int money) {
super(name, money);
}

public void receive(ArrayList<Double> list) {
//随机获取一个集合中的索引编号
int index = new Random().nextInt(list.size());
//根据索引,从集合中删除,得到被删除的红包金额
double delta = list.remove(index);
//加法,重新设置剩余金额
super.setMoney(super.getMoney() + delta);
}
}
  • 主类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public static void main(String[] args) {
Manager manager = new Manager("hxx", 100);
Member one = new Member("qzy", 0);
Member two = new Member("zyx", 0);
Member third = new Member("wn", 0);
Member four = new Member("hxs",0);
//发红包
ArrayList<Double> list = manager.send(3.1, 4);
//分红包
one.receive(list);
two.receive(list);
third.receive(list);
four.receive(list);

manager.show();

one.show();
two.show();
third.show();
four.show();
}
  • 运行结果
1
2
3
4
5
我叫:hxx剩余金额:96.9
我叫:qzy剩余金额:0.56
我叫:zyx剩余金额:0.66
我叫:wn剩余金额:0.67
我叫:hxs剩余金额:1.21