用户类
package com.wenliang;
public class User {
private String name;//姓名
private int money;//金额
//展示下当前有多少钱
public void show(){
System.out.println("我叫"+name+",我有"+money+"元钱");
}
public User() {
}
public User(String name, int money) {
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;
}
}
群主类
package com.wenliang;
import java.util.ArrayList;
public class Manager extends User {
public Manager() {
}
public Manager(String name, int money) {
super(name, money);
}
//发红包
public ArrayList<Integer> giveRed( int totalmoney,int count){
//创建一个集合来存放红包
ArrayList<Integer> list = new ArrayList<>();
//获取当前账号的金额
int money = super.getMoney();
//判断当前金额是否小于发红包总额
if (money<totalmoney){
System.out.print("余额不足");
return list;
}
//减去发的红包
super.setMoney(money-totalmoney);
int detal = totalmoney%count;
for (int i = 0; i <count-1 ; i++) {
list.add(totalmoney/count);
}
// for (int i = 0; i <list.size() ; i++) {
// System.out.print("数组内容:"+list.get(i)+" ");
// }
//如果有余数,就把余数放进最后一个红包。
list.add(totalmoney/count+detal);
return list;
}
}
群员类
package com.wenliang;
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 getRed(ArrayList<Integer> list) {
//随机获得集合里的一个红包
int index = new Random().nextInt(list.size());
//得到抢到的红包的金额
Integer detal = list.remove(index);
int money = super.getMoney();
//加到自己的金额里面
super.setMoney(money+detal);
}
}
测试类
package com.wenliang;
import java.util.ArrayList;
public class testRed {
public static void main(String[] args) {
//创建群主实例
Manager manager = new Manager();
manager.setName("王思聪");
manager.setMoney(100);
manager.show();
// 创建群员实例
Member a = new Member("A", 0);
Member b = new Member("B", 0);
Member c = new Member("C", 0);
Member d = new Member("D", 0);
Member e = new Member("E", 0);
a.show();
b.show();
c.show();
d.show();
e.show();
ArrayList<Integer> list = manager.giveRed(120, 5);
if (list.isEmpty()){
}
else
{
a.show();
b.show();
c.show();
d.show();
e.show();
}
}
}
文章就不一一概述了,代码里面注释还是挺多的。