1. 程式人生 > 其它 >群主發紅包——java學習

群主發紅包——java學習

package com.cn.test;
//父類 使用者
public class User {
    private String name;
    private int money;

    public User() {
    }

    public User(String name, int money) {
        this.name = name;
        this.money = money;
    }

    public void show(){
        System.out.println("我叫:"+name+";我有多少錢:"+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.cn.test;

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 receive(ArrayList<Integer> list){
        //抽取隨機紅包
        int index = new Random().nextInt(list.size());

        //收到紅包,就是刪除掉一個
        int delete =list.remove(index);

        //自己的餘額
        int money = super.getMoney();

        super.setMoney(money+delete);
    }
package com.cn.test;

import java.util.ArrayList;

//群主
public class Admin  extends User{
    public Admin() {
    }

    public Admin(String name, int money) {
        super(name, money);
    }

    //群主發紅包 totalMoney:發多少錢  count:發多少次
    public ArrayList<Integer> send(int totalMoney,int count){
        //需要一個集合存放紅包
        ArrayList<Integer> readList = new ArrayList<>();

        //群主餘額有多少
        int leftMoney = super.getMoney();

        //餘額不夠,不發
        if(totalMoney>leftMoney){
            System.out.println("餘額不足");
            return readList;
        }

        //扣錢,其實就是重新設定餘額
       super.setMoney(leftMoney-totalMoney);


        //求平均
        int avg = totalMoney / count;
        int mod = totalMoney % count;//餘數

        //遍歷能除盡的,
        for (int i = 0; i < count-1; i++) {
            readList.add(avg);
        }
        //多出的是最後一個紅包
        int last = avg + mod;
        readList.add(last);
        return readList;


    }

}

package com.cn.test;

import java.util.ArrayList;

public class TestClass {

    public static void main(String[] args) {

     Admin admin = new Admin("群主",100);

     Member memberA = new Member("成員A",0);
     Member memberB = new Member("成員B",0);
     Member memberC = new Member("成員C",0);

     admin.show();
     memberA.show();
     memberB.show();
     memberC.show();
     System.out.println("=====================");

     ArrayList<Integer> arrayList = admin.send(25,3);
     memberA.receive(arrayList);
     memberB.receive(arrayList);
     memberC.receive(arrayList);

        admin.show();
        memberA.show();
        memberB.show();
        memberC.show();
        System.out.println("=====================");

    }

}