随机生成卡号,并要求唯一

思想:判断是否重复,需要遍历系统中所有用户的卡号,如果系统中已经存在该卡号,需要再随机生成一次,直到随机生成的卡号系统中不存在,会用到死循环。

public class RandomCardId {
    public static String RandomCardId(ArrayList<Account> accounts){
        while (true) {
//若生成的卡号一直是重复的,则acc就不是null,会一直执行死循环,直到return cardId结束该方法
            Random ran=new Random();
            String cardId="";
            for (int i = 0; i < 8; i++) {
                int a=ran.nextInt(10);
                cardId=cardId + a;
            }
            Account acc=getAccountbyCardId( accounts,cardId);
            if(acc == null){
                return cardId;
            }
        }
    }

//定义一个判断随机生成的卡号是否已经存在的方法
    public static Account getAccountbyCardId(ArrayList<Account> accounts,String CardId){
        for (int i = 0; i < accounts.size(); i++) {
            if(accounts.get(i).getCardId().equals(CardId)){
                return accounts.get(i);
                //返回Account账户,表明生成的卡号是该用户的卡号,不能使用,需要再生成一次
            }
        }
        return null;//返回null,表明生成的卡号与系统中已有的卡号没有重复,可以使用
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值