I want to generate four random numbers in the range of 0 to 9. It's easy to generate four random numbers with Java Random.
Random random = new Random();
int numbers[] = new int[4];
for(int i=0;i<4;i++){
numbers[i] = random.nextInt(10);
}
With this I can get an array of four numbers like, 9369, 4702 etc.
Here I want to get all four digit in above array to be unique so that I can get output like 9543, 1234 etc.
For this, I have thought a way like this
- Generate a random number and assigned as first number,
- Generate a random number and check with first number if different assigned as second number else generate random number again and repeat and so on.
Is there any better way to do this so that I can get four unique random numbers easily and quickly ?
Any kind of suggestion is appreciated.
Aucun commentaire:
Enregistrer un commentaire