java怎么拦截某个对象
245
2023-02-17
Java实现发红包功能
java发红包案例,供大家参考,具体内容如下
首先我们需要分析这个代码的架构是什么,需要什么类组成等。
我们需要建立4个类,这4个类分别是用户类、群主类、成员类,运行类;
因为群主类和成员类都有共同的特点--------拥有名字和余额,所以需要用户类去存储名字与余额
第一步:我们需要建立一个用户类,里面存储的是名字和余额
package Java.RedPacketCode;
public class UserClass {
private String name;
private int balance;
public UserClass(String name, int balance) {
this.name = name;
this.balance = balance;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setBalance(int balance) {
this.balance = balance;
}
public int getBalance() {
return balance;
}
public void show() {
System.out.println("Name:" + name + "****" + "RMB:" + balance);
}
}
第二步:我们需要一个群主类去继承用户类
package Java.RedPacketCode;
import java.util.ArrayList;
public class GroupMainClass extends UserClass {
public GroupMainClass(String name, int balance) {
super(name, balance);
}
public ArrayList
int existingAmount = super.getBalance();
if (existingAmount < amountRequired) {
System.out.println("Your balance is insufficient!");
}
int money=existingAmount-amountRequired;
super.setBalance(money);
System.out.println(super.getName()+" has"+money+" yuan left");
int avg = amountRequired / count;
int remainder = amountRequired % count;
int decimal = avg + remainder;
ArrayList
for (int i = 0; i < count - 1; i++) {
list.add(avg);
}
list.add(decimal);
return list;
}
}
第三步:我们需要建立一个成员类去继承用户类
package Java.RedPacketCode;
import java.util.ArrayList;
import java.util.Random;
public class MemberClass extends UserClass {
public MemberClass(String name, int balance) {
super(name, balance);
}
public void redEnvelopes(ArrayList
Random r = new Random();
int index = r.nextInt(list.size());
int money = list.remove(index);
int existingAmount = super.getBalance();
int totalAmount = money + existingAmount;
super.setBalance(totalAmount);
}
}
第四步:我们需要建立一个运行类,用来运行代码
package Java.RedPacketCode;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
GroupMainClass gmc = new GroupMainClass("Groupleader", 200);
gmc.show();
MemberClass mc1 = new MemberClass("Tom", 0);
MemberClass mc2 = new MemberClass("Jackhttp://", 0);
MemberClass mc3 = new MemberClass("Jenny", 0);
UserClass arrays[] = {mc1, mc2, mc3};
for (int i = 0; i < arrays.length; i++) {
arrays[i].show();
}
System.out.println("==================");
Scanner scanner = new Scanner(System.in);
System.out.println("How much would you like to send");
int money = scanner.nextInt();
System.out.println("How many red packets would you like to send");
int count = scanner.nextInt();
ArrayList
mc1.redEnvelopes(list);
mc2.redEnvelopes(list);
mc3.redEnvelopes(list);
for (int i = 0; i < arrays.length; tdpRbEi++) {
arrays[i].show();
}
}
}
希望大佬们多多指教。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~