發(fā)紅包
需求:群主發(fā)普通紅包, 某群有多名成員春塌, 群主給成員發(fā)普通紅包晓避,規(guī)則為
1.群主有一筆金額, 從群主的余額中扣除只壳, 平均分成n等分俏拱, 讓成員去領
2.成員領取紅包之后,保存到成員余額中
- 定義user類
package com.neusoft.day09.redbag;
/**
* @author Eric Lee
* @date 2020/7/23 10:48
*/
public class User {
// 用戶名
private String userName;
// 余額
private int leftMoney;
public User() {
}
public User(String userName, int leftMoney) {
this.userName = userName;
this.leftMoney = leftMoney;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getLeftMoney() {
return leftMoney;
}
public void setLeftMoney(int leftMoney) {
this.leftMoney = leftMoney;
}
public void show(){
System.out.println("用戶" + userName + "\t"+"余額為" + leftMoney + "元" );
}
}
- 群主類
package com.neusoft.day09.redbag;
import java.util.ArrayList;
/**
* @author Eric Lee
* @date 2020/7/23 10:52
*/
public class Manager extends User {
public Manager() {
}
public Manager(String userName, int leftMoney) {
super(userName, leftMoney);
}
// 發(fā)紅包
public ArrayList<Integer> send(int totalMoney, int count){
ArrayList<Integer> redList = new ArrayList<>();
int leftMoney = super.getLeftMoney();
// 判斷
if(totalMoney > leftMoney){
System.out.println("余額不足");
}
// 扣錢
super.setLeftMoney(leftMoney-totalMoney);
// 每個人發(fā)的錢
int avg = totalMoney/count;
// 除不開余出來的錢
int mod = totalMoney%count;
for (int i = 0; i <count-1 ; i++) {
redList.add(avg);
}
int last = avg+mod;
redList.add(last);
return redList;
}
}
- 成員類
package com.neusoft.day09.redbag;
import java.util.ArrayList;
import java.util.Random;
/**
* @author Eric Lee
* @date 2020/7/23 10:54
*/
public class Member extends User {
public Member() {
}
public Member(String userName, int leftMoney) {
super(userName, leftMoney);
}
//收紅包
public void receive( ArrayList<Integer> list){
Random random = new Random();
int index = random.nextInt(list.size());
// Integer money = list.get(index);
// 收完之后刪除
Integer removeMoney = list.remove(index);
// 更新余額
int leftMoney = super.getLeftMoney();
int updateMoney = leftMoney +removeMoney;
super.setLeftMoney(updateMoney);
}
}
- 測試類
package com.neusoft.day09.redbag;
import java.util.ArrayList;
import java.util.Scanner;
/**
* @author Eric Lee
* @date 2020/7/23 10:54
*/
public class Test {
public static void main(String[] args) {
Manager manager = new Manager("群主", 200);
Member one = new Member("成員A", 0);
Member two = new Member("成員B", 0);
Member three = new Member("成員C", 0);
manager.show();
one.show();
two.show();
three.show();
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入金額");
int money = scanner.nextInt();
System.out.println("請輸入發(fā)幾個包");
int count = scanner.nextInt();
// 調用發(fā)紅包
ArrayList<Integer> redList = manager.send(money, count);
// 調用收紅包
one.receive(redList);
two.receive(redList);
three.receive(redList);
manager.show();
one.show();
two.show();
three.show();
}
}