原创

Java复习之-抢红包实例

红包父类:

public abstract class RedEnvelope {
    public double remainMoney;//红包当前金额
    public int remainPeople;//当前参与抢红包的人数
    public double money;//当前用户抢到的金额
    public abstract double giveMoney();//抢红包具体
}

红包类:

public class RandomRedEnvelope extends RedEnvelope {

    double minMoney;//可以抢到的最小金额
    int integerRemainMoney;//红包的钱用分表示
    int randomMoney;//给用户抢的钱
    Random random;
    RandomRedEnvelope(double remainMoney,int remainPeople){//初始化
        random = new Random();
        minMoney = 0.01;//最少1分
        this.remainMoney = remainMoney;
        this.remainPeople = remainPeople;
        integerRemainMoney = (int) (remainMoney*100);//钱用分表示
        if (integerRemainMoney<remainPeople*(int)(minMoney*100)){  //当红包初始总金额小于人数时(每人至少应该得1分)
            integerRemainMoney = remainPeople*(int)(minMoney*100); //设置一个人最少有1分可以拿
            this.remainMoney = (double)integerRemainMoney;
        }
    }

    //主要业务逻辑
    @Override
    public double giveMoney() {
        if (remainPeople <= 0) {
            return 0;//如果人数为0则结束
        }
        if (remainPeople ==1){
            money = remainMoney;//如果人数是最后一个则金额等于剩下的所有钱
            remainPeople--;//人数减1
            return money;
        }
        randomMoney = random.nextInt(integerRemainMoney);//随机一个0至剩下的金额但不包括最大值间的随机数区间
        if(randomMoney < (int)(minMoney*100)){//如果金额小于1分,则保证用户最少获得1分
            randomMoney = (int)(minMoney*100);
        }
        int leftOtherPeopleMoney = integerRemainMoney-randomMoney;//剩下的余额
        int otherPeopleNeedMoney = (remainPeople-1)*(int)(minMoney*100);//剩下的人数
        if(leftOtherPeopleMoney<otherPeopleNeedMoney){//如果剩余金额小于剩余人数
            randomMoney -= (otherPeopleNeedMoney-leftOtherPeopleMoney);
        }
        integerRemainMoney = integerRemainMoney - randomMoney;//剩余的余额
        remainMoney = (double) integerRemainMoney/100.0;//分转成元
        remainPeople--;//人数减1
        money = (double)(randomMoney/100.0);
        return money;//返回用户抢到的钱
    }
}

主函数:

public class TestMain {
    public static void main(String[] args) throws ClassNotFoundException{
        //输入初始值5.20元,人数为6人
        RedEnvelope redEnvelope = new RandomRedEnvelope(5.20,6);
        showProcess(redEnvelope);

    }

    public static void showProcess (RedEnvelope redEnvelope){
        double sum = 0;//用于事务
        while (redEnvelope.remainPeople>0){//人数大于0
            double money = redEnvelope.giveMoney();//执行抢红包
            System.out.println(money);
            sum = sum+money;
        }
        String s = String.format("%.2f",sum);//金额保留两位小数
        sum = Double.parseDouble(s);
        System.out.println(sum);
    }
}
java
  • 作者:兰总(联系作者)
  • 发表时间:2019-08-19 15:19
  • 版权声明:自由转载-非商用-保持署名
  • 公众号转载:请在文末添加作者公众号二维码
  • 评论