运用到了一个接口——Red
public interface Red {
ArrayList<Integer> devide(int totalMoney,int totalCount);
}
普通红包实现
public class CommonRed implements Red{
@Override
public ArrayList<Integer> devide(int totalMoney, int totalCount) {
ArrayList<Integer> list = new ArrayList<>();
int money = totalMoney / totalCount;
int leftMoney = totalMoney % totalMoney;
for(int i=0; i<totalCount-1; i++) {
list.add(money);
}
list.add(money+leftMoney);
return list;
}
}
手气红包实现
public class RandomRed implements Red {
@Override
public ArrayList<Integer> devide(int totalMoney, int totalCount) {
ArrayList<Integer> list = new ArrayList<>();
//随机红包最少为0.01,最多不超过平均数的二倍
int leftMoney = totalMoney;
int leftCount = totalCount;
Random r = new Random();
for(int i=0; i<totalCount - 1;i++) {
int temp = r.nextInt(leftMoney / leftCount)+1;
list.add(temp);
leftMoney -= temp;
leftCount--;
}
list.add(leftMoney);
return list;
}
}
People类
public class People {
private int money;
private String name;
private Red red;
public People() {
}
public People(String Name,int money) {
this.money = money;
this.name = name;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Red getRed() {
return red;
}
public void setRed(Red red) {
this.red = red;
}
// 在people类里面调用red的抽象方法
public ArrayList<Integer> devide(int totalMoney,int totalCount) {
return red.devide(totalMoney, totalCount);
}
}
测试main函数
public class Demo {
public static void main(String[] args) {
People people = new People("甲",100);
System.out.println("发红包准备: 1.平均红包 2、拼手气红包 输入1 or 2");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
//确定发红包的形式【 随机】或者【平均】
if(choice==1) {
people.setRed(new CommonRed());
} else if(choice==2) {
people.setRed(new RandomRed());
}else {
System.out.println("不符合");
}
//确定金额和红包个数
System.out.println("输入金额(单位/元)和红包个数(单位/个)");
double money = input.nextDouble();
int totalCount = input.nextInt();
int totalMoney = (int)(money * 100); //把金额单位变成 分
System.out.println("===================");
if(totalMoney<people.getMoney()) {
System.out.println("余额不足!!!");
}else {
ArrayList<Integer> list = people.devide(totalMoney, totalCount);
//输出list数组元素
for(int i=0;i<list.size();i++) {
System.out.println( (float) (list.get(i)*0.01) );
}
}
}
}
因为图形界面还没有掌握,所以暂时以这种形式写吧。。。