Java implementation of wechat, QQ and other group main red packet instances (ordinary red packets)

Posted by slava_php on Sat, 07 Mar 2020 10:23:47 +0100

I haven't blog for a long time

The hand is a bit raw, but it's ready to open Chang more mode!

Recently, I picked up Java knowledge again and selected some interesting cases to share with you.

Analysis:

First of all, the group leader and members are users of wechat, QQ and other applications, and they can all be classified as user classes, so we can quickly think of a very important feature in Java: inheritance.

A diagram expresses its relationship intuitively:

Secondly, analyze some logic of this program:

Suppose the group leader and the members have some money (can be 0)

A sum of money (red packet) issued by the group master shall be deducted from the balance of the group master, and divided into n equal parts on average for members to receive; after the members receive the red packet, it shall be saved in their respective balances.

Realization:

First, define the User class User:

public class User {
    // Member variables
    private String username; // User name
    private double leftMoney; // Balance, Jiao and Fen

    // Construction method
    public User() {
    }

    public User(String username, double leftMoney) {
        this.username = username;
        this.leftMoney = leftMoney;
    }
    
    // get/set method
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public double getLeftMoney() {
        return leftMoney;
    }

    public void setLeftMoney(double leftMoney) {
        this.leftMoney = leftMoney;
    }

    // How to present information
    public void show() {
        System.out.println("User name:"+ username +" , The balance is:" + leftMoney + "element");
    }
}

(TIPS) quickly create Getter/Setter methods:

Alt + Insert

Choice:

Getter and Setter

In the same way, user s can choose between parameterless method and parameterless method for quick creation:

Constructor

Select All and Select None to Select All or none.

Second, you can define the group master class Manager:

public class Manager extends User {
    // Add construction method
    public Manager() {
    }

    public Manager(String username, double leftMoney) {
        // Calling parent class construction method through super
        super(username, leftMoney);
    }
    
    public ArrayList<Double> send(double money, int count) {
        // Get group master balance
        double leftMoney = getLeftMoney();
        // If the red packet sent is greater than the remaining money of the group master, sending fails
        if(money > leftMoney) {
            System.out.println("Sending failed!");
            return null;
        }

        // Modify group master balance's
        super.setLeftMoney(leftMoney ‐ money);

        // Create a set and save the equal amount
        ArrayList<Double> list = new ArrayList<>();
    
        // Increase by 100 times, which is equivalent to converting it into 'points' to avoid the loss of precision in decimal operation
        money *= 100;
        money = (int)money;
    
        // Amount of each
        int avg = (int)(money / count);

        // Remainder not divisible
        int mod = (int)(money % count);
    
        // Whether divided or not, n ‐ 1 copy is the equal amount of each copy
        for (int i = 0; i < count ‐ 1; i++) {
            // Reduce by 100 times to 'Yuan'
            list.add(avg / 100.0);
        }
    
        // Put the last non divisible amount at the end of the list
        double last = (avg + mod)/100.0;
        list.add(last);
        
        // Return set
        return list;
    }
}

Among them, considering that the red packets sent by the group may not be integers and the number of red packets is integers, it may not be evenly distributed, so I will distribute them evenly first, and put the extra amount that cannot be evenly distributed into the last red packet.

Then, we define the Member class Member:

public class Member extends User {
    public Member() {
    }
    
    public Member(String username, double leftMoney) {
        super(username, leftMoney);
    }
    
    // To open a red packet is to take a random copy from the collection and save it to your balance
    public void receive(ArrayList<Double> list) {
    
    // Create a Random object and randomly generate a red packet number
    int index = new Random().nextInt(list.size());
    
    // Remove the corresponding number from the set to get the red packet of the amount of the number
    double delta = list.remove(index);

    // How much does the current member have
    double money = super.getLeftMoney();
    
    // Directly call the parent method and set it to the balance
    super.setLeftMoney( money + delta );
    }
}

Finally, write the execution program and execute the main function:

public class mainRedPacket {
    public static void main(String[] args) {
    // Create a group master object, three members
    Manager manager = new manager("Group owner" , 188.88);
    Member one = new Member("member A",5.23);
    Member two = new Member("member B",0);
    Member three = new Member("member C",16.89);

    // Show balance of original member
    manager.show();
    one.show();
    two.show();
    three.show();
    System.out.println("=================");
    
    // Create a keyboard entry
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter the amount of red packet sent:");
    double money = sc.nextDouble();

    // Sending red packets
    ArrayList<Double> list = manager.send(money,3);
    
    // Open the red envelope
    one.receive(list);
    two.receive(list);
    three.receive(list);

    // Display balance information
    manager.show();
    one.show();
    two.show();
    three.show();
    }
}

Results:

Send red packets three times respectively:

The first time: the group master balance is 188.88 yuan, and 200 yuan red packet is sent. Sending failed, and the balance is insufficient!

The second time: the group leader sends 18 yuan red packets, three people just divide equally, each 6 yuan.

The third time: the group leader sends 0.31 yuan red packets, and the three cannot be divided equally, so one of them is more than 0.01 yuan.

All three results are correct!

Reflection:

1. There is no control over the precision of double type, and it is likely that the precision of addition and subtraction of floating-point numbers or multiplication and division of floating-point numbers is not correct. Readers can think about it for themselves, or Baidu can solve it.

2. There are not only ordinary red envelopes, but also lucky red envelopes. You can use the knowledge of random numbers to solve this problem. Bloggers will be slower in the later stage. Welcome to give your own solution.

Thank you for your reading. Please correct the deficiencies!

 

 

Published 3 original articles, won praise 4, visitors 2153
Private letter follow

Topics: Java