Random类模拟微信发红包

//用随机数模拟微信发红包的场景

import java.util.Random;
import java.util.Scanner;

public class Demo4 {

public static void main(String[] args) {
	System.out.println("----微信抢红包----");
	Scanner sc = new Scanner(System.in);
	System.out.println("请输入红包总金额(元):");
	double total = sc.nextDouble();
	System.out.println("请输入红包个数(个 ):");
	int bagCount = sc.nextInt();	   
    
	double min = 0.01;//红包最小金额
	Random c = new Random();//随机数
	
	if(total / bagCount == 0.01) {
		for(int i = 1; i <= bagCount; i++) {
		System.out.println("第" + i + "个红包" + 0.01 + "元");
		}
	}else if(total / bagCount < 0.01) {
		System.out.println("不够分呢");
	}else {
	for(int i = 1; i < bagCount; i++) {
		/*
		 * 红包最大金额 = 总金额 - (总红包个数 - 已发出红包的个数) * 红包最小金额
		 * 随机数在0到最大金额之间,因为要产生int型,故*100将两位小数变为整数,之后再除以100还原
		 * 
		 */
		double max = total - (bagCount - i) * min;
		double bound = max - min;
		
		double safe = (double)c.nextInt((int) (bound * 100)) / 100;//nextInt(int n)返回0~n之间的随机值,n取不到
		double money = safe + min;//加上红包最小金额,以防出现0值
		total = total - money;//发出一个红包后的总金额
		 System.out.println("第" + i + "个红包" + String.format("%.2f", money) + "元");
	}
	System.out.println("第" + bagCount + "个红包" + String.format("%.2f", total) + "元");
	sc.close();
   }
}

}

你可能感兴趣的:(Random类模拟微信发红包)