本文实例为大家分享了java实现简单发红包的具体代码,供大家参考,具体内容如下
这个案例是普通红包,均分的,不是拼手气红包。
package nuc.edu.day01.demo05; /** * @author Administrator * 用户类 */ public class User { private String name; private Double money; public User() { } //显示当前余额 public void show(){ System.out.println(name + "当前的余额为:" + money); } public User(String name, Double money) { this.name = name; this.money = money; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } }
package nuc.edu.day01.demo05; import java.util.ArrayList; /** * @author Administrator * 群主发红包的操作 */ public class Manager extends User { public Manager() { } public Manager(String name, Double money) { super(name, money); } /**定义发红包的方法 * totalMoney:发红包的总金额 * num:发红包的个数*/ public ArrayList<Double> send(double totalMoney,int num){ /**存放红包的集合*/ ArrayList<Double> redList = new ArrayList<>(); /**当前余额*/ double leftMoney = super.getMoney(); if (leftMoney < totalMoney){ System.out.println("抱歉,您的余额不足"); return redList; } /**发完红包的余额*/ super.setMoney(leftMoney-totalMoney); /**将钱平均存入每个红包中*/ double avg = totalMoney / num; for (int i = 0; i < num; i++) { redList.add(avg); } return redList; } }
package nuc.edu.day01.demo05; import java.util.ArrayList; import java.util.Random; /** * @author Administrator * 群内成员抢红包的操作 */ public class Member extends User { public Member() { } public Member(String name, Double money) { super(name, money); } /**定义收红包的方法*/ public void receive(ArrayList<Double> list){ /**创建随机红包对应的索引*/ int index = new Random().nextInt(list.size()); /**当前余额*/ double money = super.getMoney(); /**根据索引将自己抢到的红包删掉*/ double delta = list.remove(index); /**领完红包后的余额*/ super.setMoney(money+delta); } }
package nuc.edu.day01.demo05; import java.util.ArrayList; /** * @author Administrator */ public class Main { public static void main(String[] args) { Manager manager = new Manager("群主",300.00); Member a = new Member("A",0.00); Member b = new Member("B",10.00); /**显示当前余额*/ manager.show(); a.show(); b.show(); System.out.println("============"); ArrayList<Double> redList = manager.send(52.00,2); a.receive(redList); b.receive(redList); /**显示抢完红包后的余额*/ manager.show(); a.show(); b.show(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。
- 本文固定链接: https://zxbcw.cn/post/200739/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)