JAVA仿微信发红包

第一步:创建一个RedPackage类

remainSize 剩余的红包数量
remainMoney 剩余的钱
public class RedPackage {
    int remainSize;
    double remainMoney;

    public void setRemainSize(int remainSize) {
        this.remainSize = remainSize;
    }

    public void setRemainMoney(double remainMoney) {
        this.remainMoney = remainMoney;
    }

    public int getRemainSize() {
        return remainSize;
    }

    public double getRemainMoney() {
        return remainMoney;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("RedPackage{");
        sb.append("remainSize=").append(remainSize);
        sb.append(", remainMoney=").append(remainMoney);
        sb.append(});
        return sb.toString();
    }
}

第二步:写一个测试类

最大红包=当前剩余钱/当前剩余红包个数×2,代码奉上

public static double getRandomMoney(RedPackage _redPackage) {
        // remainSize 剩余的红包数量
        // remainMoney 剩余的钱
        if (_redPackage.remainSize == 1) {
            _redPackage.remainSize--;
            return (double) Math.round(_redPackage.remainMoney * 100) / 100;
        }
        Random r = new Random();
        double min = 0.01; //
        double max = _redPackage.remainMoney / _redPackage.remainSize * 2;
        double money = r.nextDouble() * max;
        money = money <= min ? 0.01 : money;
        money = Math.floor(money * 100) / 100;
        _redPackage.remainSize--;
        _redPackage.remainMoney -= money;
        return money;
    }

将循环出来的红包放到list里面

 /**
     * 每次产生一个红包
     *
     * @param money 总金额
     * @param count 数量
     * @return
     */
    public static List<Double> listRedPacket(double money, int count) {
        RedPackage redPackage = new RedPackage();
        List<Double> list = new ArrayList<>();
        double mon = 0;
        double mony = 0;
        for (int i = 0; i < count; i++) {
            if (i == 0) {
                redPackage.setRemainMoney(money);
                redPackage.setRemainSize(count);
                mon = getRandomMoney(redPackage);
                mony += mon;
            } else {
                redPackage.setRemainMoney(money - mony);
                redPackage.setRemainSize(count - i);
                mon = getRandomMoney(redPackage);
                mony += mon;

            }

            list.add(mon);
        }
        return list;
    }

最后:main方法调用100块钱5个包

public static void main(String[] args) {
        test redPacket = new test();for (int i = 0; i < 10; i++) {
            List<Double> list2 = redPacket.listRedPacket(100, 5);
            System.out.println(list2);
        }
    }

结果:

JAVA仿微信发红包

JAVA仿微信发红包

上一篇:不写代码,拖拖拽拽也可使用 Matplotlib/Seaborn 可视化


下一篇:java web乱码问题原因及解决方法