java 模拟微信拼手气红包程序产生指定个数的随机红包 ● 输入红包总金额 ● 输入红包个数 ● 输出所有红包
时间: 2024-05-09 13:14:28 浏览: 69
以下是 Java 实现微信拼手气红包程序,可以产生指定个数的随机红包:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class RedPacket {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入红包总金额:");
double totalAmount = scanner.nextDouble();
System.out.print("请输入红包个数:");
int num = scanner.nextInt();
List<Double> redPacketList = generateRedPacket(totalAmount, num);
System.out.println("所有红包:");
for (Double redPacket : redPacketList) {
System.out.println(redPacket);
}
}
/**
* 生成随机红包
*
* @param totalAmount 红包总金额
* @param num 红包个数
* @return 红包列表
*/
private static List<Double> generateRedPacket(double totalAmount, int num) {
List<Double> redPacketList = new ArrayList<>();
Random random = new Random();
double remainingAmount = totalAmount;
for (int i = 0; i < num; i++) {
if (i == num - 1) {
redPacketList.add(remainingAmount);
} else {
double maxAmount = remainingAmount / (num - i);
double amount = random.nextDouble() * maxAmount * 2;
redPacketList.add(amount);
remainingAmount -= amount;
}
}
return redPacketList;
}
}
```
运行程序后,输入红包总金额和红包个数,就能输出所有随机生成的红包金额。
阅读全文