拼手气红包-基于继承实现(Java萌新篇)
拼手气红包-基于继承实现(Java萌新篇)
题目:
群主发拼手气红包,n名群员收红包;
实现群主随机发送n份总金额数目一定的红包,群员收到红包,然后输出提示信息;
PS.该程序较为简单,没有检查功能,仅供参考。
程序代码:
//首先,我们创建一个抽象父类,为成员共有属性。
public abstract class PeopleFather {
//共有属性:名字
public String name;
//共有属性:余额
public int totalmoney;
}
//第二步,创建群主成员类,实现发送红包方法
public class OrganizationPeople extends PeopleFather{
public OrganizationPeople(String name){
this.name=name;//构造方法,创建群主的名字
}
public int num;//红包份数
//发送红包方法
public ArrayList transmit(){
Random r = new Random();
int totalmoney =0;//红包总金额
int num = 0;//红包份数
Scanner sc = new Scanner(System.in);
ArrayList list = new ArrayList<>();
System.out.print("请输入发送的红包总金额:");
totalmoney = sc.nextInt();
System.out.print("请输入发送的红包个数:");
num = sc.nextInt();
int sum = 0;
//将总金额随机分为n份红包
for (int i = 0; i < num-1; i++) {
int temp = totalmoney-sum;
int rand = r.nextInt(temp);
list.add(rand);
sum+=rand;
}
int last = totalmoney-sum;//将最后一份插入list中
list.add(last);
System.out.println(this.name+"群主发送了"+num+"份"+"总计"+totalmoney+"元拼手气红包!");
return list;
}
}
//第三步,创建成员类,用于接受红包
public class PeopleMan extends PeopleFather{
public PeopleMan(String name){
this.name=name;
}
//收到红包
public void getMoney(ArrayList list,int index){
//System.out.println(name+"收到红包,余额为"+remainingSum);
int i = index-1;
this.totalmoney=list.get(i);
System.out.println(this.name+"抢到了"+this.totalmoney+"元的红包!");
}
}
//第四步,主类实现创建群主、创建n名成员,得到提示信息
public static void main(String[] args) {
//创建群主
OrganizationPeople or = new OrganizationPeople("玛瑙石");
//创建n名成员
PeopleMan pm = new PeopleMan("放飞梦想");
PeopleMan pm1 = new PeopleMan("可乐加冰");
PeopleMan pm2 = new PeopleMan("爱我走心");
PeopleMan pm3 = new PeopleMan("我爱茉莉清茶");
PeopleMan pm4 = new PeopleMan("白赚之哥");
//群主发送红包
ArrayList list = or.transmit();
//成员接受红包
pm.getMoney(list,1);
pm1.getMoney(list,2);
pm2.getMoney(list,3);
pm3.getMoney(list,4);
pm4.getMoney(list,5);
}
实现截图:
拼手气红包-基于继承实现(Java萌新篇)相关教程