写了一个微信发红包的代码

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class WeChatClub {

    public static void main(String[] args) {

        int sendMoney = 10000; // 100元
        int size = 6; // 红包个数

        Person zhangsan = new Person("1", "张三");

        Person lisi = new Person("2", "李四");
        Person wangwu = new Person("3", "王五");
        Person zhao6 = new Person("4", "赵六");
        Person mrLi = new Person("5", "李总");
        Person missX = new Person("6", "小波");
        Person missLxb = new Person("7", "李晓波");
        Person missF = new Person("8", "冯程程");


        List redPackets = zhangsan.sendMoney(sendMoney, size);
        lisi.receiveMoney(redPackets);
        wangwu.receiveMoney(redPackets);
        zhao6.receiveMoney(redPackets);
        mrLi.receiveMoney(redPackets);
        missX.receiveMoney(redPackets);
        missLxb.receiveMoney(redPackets);
        missF.receiveMoney(redPackets);

    }


}

class Person implements Serializable {

    // 唯一标识
    private String id;
    // 昵称
    private String nickName;

    // 抢到的红包金额单位: 分
    private int money;

    public Person() {
    }

    public Person(String id, String nickName) {
        this.id = id;
        this.nickName = nickName;
    }

    // getter, setter

    public String getId() {
        return id;
    }

    public String getNickName() {
        return nickName;
    }

    public int getMoney() {
        return money;
    }


    /**
     * 发红包
     *
     * @param amount 红包金额, 单位为分
     * @param size   红包份数
     * @return
     */
    public List sendMoney(int amount, int size) {
        System.out.println(nickName + "发了 " + size + " 个红包金额: " + amount);

        List redPackets = new ArrayList<>();

        BigDecimal bdAmount = new BigDecimal(amount);

        for (int i = 0; i < size; i++) {

            if (i == size - 1) {
                redPackets.add(bdAmount.intValue());
            } else {

                BigDecimal percent = new BigDecimal(new Random().nextInt(100)).divide(new BigDecimal(100));
                BigDecimal redPacket = bdAmount.multiply(percent).setScale(0, BigDecimal.ROUND_HALF_UP);

                redPackets.add(redPacket.intValue());

                bdAmount = bdAmount.subtract(redPacket);
            }

        }

        return redPackets;

    }

    /**
     * 抢红包
     *
     * @param redPackets
     * @return
     */
    public synchronized void receiveMoney(List redPackets) {

        if (redPackets == null || redPackets.isEmpty()) {
            System.out.println(nickName + " 没抢到红包, 红包被抢完了");
            return;
        }

        int anInt = new Random().nextInt(redPackets.size());

        this.money = redPackets.remove(anInt);

        System.out.println(nickName + "抢到了红包, 金额: " + money);

    }
}

你可能感兴趣的:(java)