请用Java写一个发红包的代码,参数有红包总金额,红包个数,可以控制2个包尾数为7
时间: 2024-03-14 17:47:23 浏览: 129
好的,以下是一个可以控制2个包尾数为7的Java程序,用于发放红包,其中参数为红包总金额和红包个数:
```
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RedPacket {
private static final int MAX_SCALE = 2;
private static final int RANDOM_COUNT = 20;
public static List<BigDecimal> divideRedPacket(BigDecimal totalAmount, int totalCount) {
if (totalAmount == null || totalCount <= 0) {
return null;
}
List<BigDecimal> result = new ArrayList<>();
BigDecimal currentAmount = BigDecimal.ZERO;
for (int i = 1; i <= totalCount; i++) {
if (i == totalCount) {
BigDecimal lastAmount = totalAmount.subtract(currentAmount);
if (lastAmount.setScale(2).doubleValue() % 10 == 7) {
result.add(lastAmount);
} else {
result.add(lastAmount.subtract(BigDecimal.valueOf(lastAmount.setScale(2).doubleValue() % 10)).add(BigDecimal.valueOf(7)));
}
} else {
BigDecimal maxAmount = totalAmount.subtract(currentAmount).subtract(BigDecimal.valueOf(totalCount - i));
BigDecimal randomAmount = getRandomAmount(maxAmount, totalCount - i);
if (randomAmount.setScale(2).doubleValue() % 10 == 7) {
result.add(randomAmount);
} else {
result.add(randomAmount.subtract(BigDecimal.valueOf(randomAmount.setScale(2).doubleValue() % 10)).add(BigDecimal.valueOf(7)));
}
currentAmount = currentAmount.add(result.get(i-1));
}
}
return result;
}
private static BigDecimal getRandomAmount(BigDecimal maxAmount, int count) {
BigDecimal randomAmount = BigDecimal.ZERO;
Random random = new Random();
int scale = maxAmount.scale() <= MAX_SCALE ? maxAmount.scale() : MAX_SCALE;
for (int i = 1; i <= RANDOM_COUNT; i++) {
randomAmount = maxAmount.multiply(BigDecimal.valueOf(random.nextDouble())).setScale(scale, BigDecimal.ROUND_HALF_UP);
if (randomAmount.compareTo(BigDecimal.ZERO) > 0 && randomAmount.compareTo(maxAmount.divide(BigDecimal.valueOf(count), scale, BigDecimal.ROUND_HALF_UP)) <= 0) {
break;
}
}
return randomAmount;
}
public static void main(String[] args) {
BigDecimal totalAmount = BigDecimal.valueOf(1000);
int totalCount = 10;
List<BigDecimal> result = divideRedPacket(totalAmount, totalCount);
if (result == null) {
System.out.println("参数错误");
return;
}
for (BigDecimal amount : result) {
if (amount != null) {
System.out.println(amount.setScale(2, BigDecimal.ROUND_HALF_UP));
}
}
}
}
```
请注意,上面的代码仅作为示例,实际应用中可能需要更严格的参数校验和算法优化。同时,如果您想控制2个包尾数为7,可以在程序中使用if语句来判断,并对不符合条件的金额进行调整,以保证最终的结果符合要求。
阅读全文