lundi 26 novembre 2018

check unrepeated random number

I have a method that return a number:

  public String getNum()
   {
    Random random = new Random();
    return random.nextInt(1000) + "";
   }

And I have this method that stores an object

public void store(User user)
{
  String str = getNum();
  user.setIdCode(str);
  for (User users: userList)
  { 
    if(users.getId() == user.getId())
{
user.setIdCode(getNum);
}

  }

}

if Id is excited than re-set the id. This is for sure checks if the id exists the first time but how about the second time that id is set. there would be a possibility of repeating the same number. At the same time we cant go in infinite loop.




Aucun commentaire:

Enregistrer un commentaire