java实现发红包收红包案例

1:定义一个父类

public class User {
     
	private String name;
	private int money;
	public User() {
     
		super();
		// TODO Auto-generated constructor stub
	}
	public User(String name, int  money) {
     
		super();
		this.name = name;
		this.money = money;
	}
	public String getName() {
     
		return name;
	}
	public void setName(String name) {
     
		this.name = name;
	}
	public int getMoney() {
     
		return money;
	}
	public void setMoney(int money) {
     
		this.money = money;
	}
}

2:群主发红包

public class Manager extends User{
     

	public Manager() {
     
		super();
		// TODO Auto-generated constructor stub
	}

	public Manager(String name, int money) {
     
		super(name, money);
		// TODO Auto-generated constructor stub
	}
	public void show() {
     
		System.out.println("我叫"+this.getName()+",我有"+this.getMoney()+"钱");
	}
	public ArrayList<Integer> send(int totalmoney,int count) {
     
		ArrayList<Integer> list = new ArrayList<>();
		int haveMoney = super.getMoney();
		if(totalmoney>haveMoney) {
     
			System.out.println("你的余额不足");
			return list;
		}
		super.setMoney(haveMoney-totalmoney);//重新设置剩余的money
		int avg = totalmoney/count;
		int mod = totalmoney%count;//如果有余数
		for(int i = 0;i<count-1;i++) {
     //最后一个单独算
			list.add(avg);//把红包额放在list中
		}
		int left = avg+mod;
		list.add(left);//把最后一个也放在list中
		return list;
	}
}

成员收红包

public class Member extends User{
     

	public Member() {
     
		super();
		// TODO Auto-generated constructor stub
	}

	public Member(String name, int money) {
     
		super(name, money);
		// TODO Auto-generated constructor stub
	}
	public void show() {
     
		System.out.println("我叫"+this.getName()+",我有"+this.getMoney()+"钱");
	}
	public void receive(ArrayList<Integer> list) {
     
		int index = new Random().nextInt(list.size());//这里返回的是集合的一个随机索引。
		//根据索引从list中删除红包,这个删除的红包就是自己得到的红包
		int getMoney = list.remove(index);
		int haveMoney = super.getMoney();
		int totalMoney = haveMoney+getMoney;//自己的总钱数变为原来有的加上这里领的
		super.setMoney(totalMoney);
	}
}
public class RedTest {
     

	public static void main(String[] args) {
     
		// TODO Auto-generated method stub
		Manager ma = new Manager("群主",100);
		Member meA = new Member("成员A",0);
		Member meB = new Member("成员B",0);
		Member meC = new Member("成员C",0);
		ma.show();
		meA.show();
		meB.show();
		meC.show();
		
		ArrayList<Integer> list = ma.send(20, 3);
		meA.receive(list);
		meB.receive(list);
		meC.receive(list);
		ma.show();//打印群主所剩的红包
		meA.show();//打印成员所剩的红包
		meB.show();
		meC.show();
	}
}

你可能感兴趣的:(java)