Main.java
package redEnvelope; import java.util.Scanner; public class Main { public static void main(String[] args) { //红包金额和人数 double money = 0; int people = 0; System.out.println("请输入红包的大小和人数"); Scanner reader = new Scanner(System.in); money = reader.nextDouble(); people = reader.nextInt(); //保证每人至少一分钱 while((money<(people*RandomRedEnvelope.minMoney)) || (people <= 0)){ System.out.println("输入金额或人数不支持!请重新输入红包的大小和人数:"); money = reader.nextDouble(); people = reader.nextInt(); } //构建一个抢红包实例 RandomRedEnvelope randomRedEnvelope = new RandomRedEnvelope(money, people); System.out.printf("%.2f红包已被%d个人抢完,结果如下:n", money, people); showProgress(randomRedEnvelope); } public static void showProgress(RandomRedEnvelope randomRedEnvelope){ while(randomRedEnvelope.remainPeople>0){ double money = randomRedEnvelope.giveMoney(); System.out.printf("%.2ft",money); } } }
RedEnvelope.java
package redEnvelope; public abstract class RedEnvelope { public double remainMoney; //红包当前金额 public int remainPeople; //抢红包的人数 public abstract double giveMoney(); //抢红包方法 }
RandomRedEnvelope.java
package redEnvelope; import java.util.Random; public class RandomRedEnvelope extends RedEnvelope{ //随机红包 double money = 0; //最后用户得到的金额 int randomMoney = 0; //系统随机产生的金额 public static double minMoney = 0.01; //设置红包最小金额为1分钱 int integerRemainMoney; //红包当前金额用分表示 int integerMinMoney; //红包最小金额用分表示 RandomRedEnvelope(double remainMoney, int remainPeople){ //设置红包的大小,抢的人数,每人至少抢到的金额 this.remainMoney = remainMoney; this.remainPeople = remainPeople; integerRemainMoney = (int)remainMoney*100; integerMinMoney = (int)(minMoney*100); } public double giveMoney(){ //重写抽象方法中抢红包实例 if(remainPeople == 1){ money = remainMoney; remainPeople--; return money; } Random random = new Random(); randomMoney = random.nextInt(integerRemainMoney); //如果随机产生的钱太小,那这个红包的钱就是一分 if(randomMoney < integerMinMoney){ randomMoney = integerMinMoney; } //剩余用来抢的钱 int leftOtherPeopleMoney = integerRemainMoney - randomMoney; //其他人至少能得到的钱 int otherPeopleNeedNoney = integerMinMoney*(remainPeople-1); if(leftOtherPeopleMoney < otherPeopleNeedNoney){ randomMoney -= (otherPeopleNeedNoney - leftOtherPeopleMoney); } integerRemainMoney -= randomMoney; remainMoney = (double)(integerRemainMoney/100.0); remainPeople--; money = (randomMoney/100.0); return money; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)