java實現紅包隨機分配金額
import java.util.Random;
class Scratch {
public static void main(String[] args) {
int count = 5;/個數
double amount = 200;/金額
double singleMin = 0.01;//單個紅包最小金額
double singleMax = 200.00;//單個紅包最大金額
double money = 0;
for (int i = 0, len = count; i < len; i++) {//模擬'count'個人搶紅包,
money = test(count--, amount -= money, singleMin, singleMax);
System.out.println(String.format("第%s個人搶到紅包:%s", i + 1, money));
}
}
/**
* @param count 個數
* @param amount 紅包總金額
* @param singleMin 單個紅包最小金額
* @param singleMax 單個紅包最大金額
*/
private static double test(int count, double amount, double singleMin, double singleMax) throws UnsupportedOperationException {
if (amount > singleMax || amount < singleMin) {
throw new UnsupportedOperationException(String.format("金額不能大於%s,不能小於%s", singleMax, singleMin));
}
if (count * singleMin > amount) {
throw new UnsupportedOperationException(String.format("金額不足夠發%s個紅包", count));
}
if (count == 1) {
return (double) Math.round(amount * 100) / 100;//剩餘最後一個
}
double min = 0.01;//當前紅包的最小金額
double max = amount / count * 2;//當前紅包的最大金額
double money = new Random().nextDouble() * max;/金額
money = money <= min ? min : Math.floor(money * 100) / 100;//特殊處理,保留2位小數,四捨五入
return money;
}
}