Java.常用实用类

用java程序模拟抢红包。这里给出的随机抢红包算法比较简单。

例如,假设当前红包是5.2元,参与抢红包的人是6个人,那么第一个人抢到的金额m是一个在0~519的随机数(用分表示钱的金额)。

如果m是0,需要把m赋值成1(保证用户至少能够抢到1分钱);

如果m不是0,那么520-m是剩余的金额,要求剩余的金额必须保证其余5个人都至少能够抢到1分钱,否则m要减去多抢到的金额。

代码运行结果:

//RedEnvelope

public abstract class RedEnvelope {
	public double remainMoney;//红包当前金额
	public int remainPeople;//当前参与抢红包的人数
	public double money;//当前用户抢到的金额
	public abstract double giveMoney();//抽象方法,具体怎么抢红包由子类完成
	
}


//RandomRedEnvelope
import java.util.*;

public class RandomRedEnvelope extends RedEnvelope{
	double minMoney;//可以抢到的最小金额
	int integerRemainMoney;//红包中的钱用分表示
	int randomMoney;//给用户抢的钱
	Random random;
	RandomRedEnvelope(double remainMoney,int remainPeople)
	{
		random=new Random();
		minMoney=0.01;
		this.remainMoney=remainMoney;
		this.remainPeople=remainPeople;
		integerRemainMoney=(int)(remainMoney*100);
		if(integerRemainMoney<remainPeople*(int)(minMoney*100))
		{
			integerRemainMoney=remainPeople*(int)(minMoney*100);
			this.remainMoney=(double)integerRemainMoney;
		}
		
		
	}
	public double giveMoney()
	{
		if(remainPeople<=0)
		{
			return 0;
		}
		if(remainPeople==1)
		{
			money=remainMoney;
			remainPeople--;
			return money;
		}
		randomMoney=random.nextInt(integerRemainMoney);
		if(randomMoney<(int)(minMoney*100))
		{
			randomMoney=(int)(minMoney*100);
		}
		int leftOtherPeopleMoney=integerRemainMoney-randomMoney;//当前用户留给其他人的金额
		int otherPeopleNeedMoney=(remainPeople-1)*(int)(minMoney*100);//保证其他人能够继续抢的最少金额
		if(leftOtherPeopleMoney<otherPeopleNeedMoney)
		{
			randomMoney-=(otherPeopleNeedMoney-leftOtherPeopleMoney);
		}
		integerRemainMoney-=randomMoney;
		remainMoney=(double)(integerRemainMoney/100.0);//将剩余的钱转化为元
		remainPeople--;
		money=(double)(randomMoney/100.0);
		return money;
		
	}

}

public class example {
	public static void main(String []args)
	{
		RedEnvelope redEnvelope=new RandomRedEnvelope(5.20,6);
		System.out.printf("用以下循环输出%d个人抢%.2f元的随机红包:\n",redEnvelope.remainPeople,redEnvelope.remainMoney);
		showProcess(redEnvelope);
	}
	public static void showProcess(RedEnvelope redEnvelope)
	{
		double sum=0;
		while(redEnvelope.remainPeople>0)
		{
			double money=redEnvelope.giveMoney();
			System.out.printf("%.2f\t",money);
			sum+=money;
		}
		String s=String.format("%.2f", sum);
		sum=Double.parseDouble(s);
		System.out.printf("\n%.2f的红包被抢完", sum);
	}

}

欢迎批评指正!

  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数字漫游者

力图简洁c++,创作不易,谢谢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值