发红包小游戏

    科技2024-08-16  38

    题目 群主发普通红包。某群有多名成员,群主给成员发普通红包。普通红包的规则: 1. 群主的一笔金额,从群主余额中扣除,平均分成n等份,让成员领取。 2. 成员领取红包后,保存到成员余额中。

    分析 具体实现

    //抽象用户类 public class User { private String name;//姓名 private int money;//余额 public User() {} public User(String name,int money) { this.money=money; this.name=name; } public void setName(String name) { this.name = name; } public void setMoney(int money) { this.money = money; } public String getName() { return name; } public int getMoney() { return money; } public void show() { System.out.println("我叫"+name+"余额"+money); } } //群主类 import java.util.ArrayList; //群主的类 public class Manamer extends User { public Manamer() { } public Manamer(String name,int money) { super(name,money); } public ArrayList<Integer>send(int totalMoney,int count) { ArrayList<Integer> redList=new ArrayList<>(); int leftMoney=super.getMoney(); if(totalMoney>leftMoney) { System.out.println("余额不足"); return redList; } super.setMoney(leftMoney-totalMoney); //发红包需平均拆分count分 int avg=totalMoney/count; int mod=totalMoney%count; for (int i = 0; i < count-1; i++) { redList.add(avg); } int last=avg+mod; redList.add(last); return redList; } } //成员类 import java.util.ArrayList; import java.util.Random; public class Member extends User{ public Member() {} public Member(String name,int money) { super(name,money); } public void receiver(ArrayList<Integer> list) { int index=new Random().nextInt(list.size()); int delta=list.remove(index); int money=super.getMoney(); super.setMoney(money+delta); } } 主函数 import java.util.ArrayList; public class Main { public static void main(String[] args) { Manamer manamer=new Manamer("群主",100); Member one=new Member("成员A",0); Member two=new Member("成员B",0); Member three=new Member("成员C",0); manamer.show(); one.show(); two.show(); three.show(); ArrayList<Integer> redList=manamer.send(20,3); one.receiver(redList); two.receiver(redList); three.receiver(redList); manamer.show(); one.show(); two.show(); three.show(); } }
    Processed: 0.009, SQL: 8