思想:判断是否重复,需要遍历系统中所有用户的卡号,如果系统中已经存在该卡号,需要再随机生成一次,直到随机生成的卡号系统中不存在,会用到死循环。
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,表明生成的卡号与系统中已有的卡号没有重复,可以使用 } }