【Java】发红包案例——平均和手气红包两种

运用到了一个接口——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) );
			}
		}		
	}
}

因为图形界面还没有掌握,所以暂时以这种形式写吧。。。

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值