-1

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.

  • [How do I compare strings in Java?](https://stackoverflow.com/q/513832/5221149) – Andreas Nov 26 '18 at 17:55
  • 1
    Possible duplicate of [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – stdunbar Nov 26 '18 at 21:41
  • @stdunbar I think OP is not asking about the why it gets wrong, he is more concerned about what if duplicate id is given to another user. – PradyumanDixit Nov 27 '18 at 03:31
  • Hey @MajdaElferjani do mark the answer as correct by clicking the V type tick mark looking button next to the answer, this helps future readers of the question on SO and I'd appreciate that too. Cheers! :) – PradyumanDixit Dec 26 '18 at 04:17

1 Answers1

0

What you can try is add a few random numbers in a Set and then use them separately whenever you want.

What I mean by it is that if you're trying to get a random number every time, you can just store some random numbers at once and then retrieve them one by one when you need them.

In code, put this in some method called storeRandomNumbers() and call it in the beginning of your program. Also, declare the Set as a global variable.

You can also make a separate variable to keep track of how many random numbers have been used up and use it to retrieve the next random number from the Set.

The code would look something like this (makes changes according to your needs):

Random rand = new Random();
Set<Integer> uniqueRandoms = new HashSet<>();
while (uniqueRandoms.size()<10){
    uniqueRandoms.add(rand.nextInt(11));
}
for (Integer i : uniqueRandoms){
    // System.out.print(i+" ");
    // retrieve them from here and use them whenever you want
}

Edit: Yes as @Andreas gave the link to suggest, you don't compare Strings with ==, rather you use the equals() method.

PradyumanDixit
  • 2,372
  • 2
  • 12
  • 20