Java基础:拼多多砍一刀项目
任务要求
需求说明: (认真看需求分析)
完成如上砍一刀功能接口开发,用户点击‘帮好友砍一刀’,进行砍价。
需求分析
1.用户点击 ‘帮好友砍一刀’ 给该用户砍掉部分金额。
2.每个用户只能砍价一次。 不得多次砍价
3.当砍价金额为0时,砍价失败。
4.砍价中均为整数类型的砍价,不带小数点,比如:砍价80,100等等
业务提示
1.模拟一个初始需要砍价的用户的名称,和砍价金额, 总金额。(用JavaBean存储需要被砍价用户信息)(5分)
2.用户点击,进行金额随机减少,并且记录砍价用户和砍价金额。(用集合存储砍价用户信息)(5分)
3.展示砍价信息,如上图:需要展示 被砍人金额,相差金额,砍价人以及金额信息(5分)
4.按照实际砍价业务需求,有可能很多人都没有把价格砍为0,为了防止这个问题出现,我们假设最多有10个人就可以把价格砍为0(假设阈值= 10 那么也就是当砍价人数达到10就能砍价成功,也就是最后一个人直接砍完剩下的金额即可)(10分)
需求效果图
输入砍价用户进行随机金额砍价
相同用户不能重复砍价
砍价金额达到需要,结束砍价
解题步骤
账户类
public class Account {
private String name;
private int bargainingAmount;
private int totalAmount;
public Account() {
}
public Account(String name, int totalAmount, int bargainingAmount) {
this.name = name;
this.totalAmount = totalAmount;
this.bargainingAmount = bargainingAmount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBargainingAmount() {
return bargainingAmount;
}
public void setBargainingAmount(int bargainingAmount) {
this.bargainingAmount = bargainingAmount;
}
public int getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(int totalAmount) {
this.totalAmount = totalAmount;
}
}
测试类
public class Test {
public static void main(String[] args) {
ArrayList<Account> cutlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
Random random = new Random();
Account account = new Account("光头强", 80, 0);
int i=0;
while (true) {
System.out.println("*****************************************");
System.out.println("*****************************************");
System.out.println("已砍" + account.getBargainingAmount() + ",还差" + account.getTotalAmount() + "元");
System.out.println("----------------------->砍价帮<-----------------------");
//遍历集合,查询已经砍过的用户
for (Account value : cutlist) {
System.out.println(value.getName() + "----- 砍掉" + value.getBargainingAmount());
}
//输入用户名
System.out.println("是否砍价(输入砍价用户名)");
Account cutPerson = new Account();
String name = scanner.next();
//并检查是否有重复,输出true说明有相同的,输出false说明没有相同的
if (checkName(cutlist,name)){
System.out.println("已看过用户不能重复砍价....");
continue;
}
cutPerson.setName(name);
i++;
//如果这是第十个人则砍价必定成功
if (i == 10) {
cutPerson.setBargainingAmount(account.getTotalAmount());
}else {
//生成小于还剩金额的随机数
int money = random.nextInt(account.getTotalAmount());
cutPerson.setBargainingAmount(money+1);
}
cutlist.add(cutPerson);
System.out.println("砍价成功:" + cutPerson.getName() + "为" + account.getName() + "砍掉" + cutPerson.getBargainingAmount());
//修改被砍账户数据
account.setBargainingAmount(account.getBargainingAmount() + cutPerson.getBargainingAmount());
account.setTotalAmount(account.getTotalAmount() - cutPerson.getBargainingAmount());
//如果总金额降为0则结束循环
if(account.getTotalAmount()==0){
System.out.println("砍价结束");
break;
}
}
}
private static boolean checkName(ArrayList<Account> cutlist,String name) {
boolean check = false;
for (Account value:cutlist){
if(value.getName().equals(name)){
return true;
}
}
return check;
}
}