如何用Java实现一个微信抢红包的过程呢?
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("%.2f\t",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;
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;
}
}
|