I want to generate four random numbers ranging from 0 to 9. It is easy to generate four random numbers with the Java Random class.
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 easily get an array of four numbers, 9369 , 4702 , etc. In this case, it may be possible to repeat a number in four numbers, and I do not want this to be repeated in numbers.
Here I want all four digits in the above array to be unique so that I can get output, like 9543 , 1234 , etc.
For this, I thought about the following.
- Create a random number and assign it as the first number.
- Create a random number and check with the first number, if another is assigned the second number, generate a random number again and repeat, etc.
Is there a better way than the method above so that I can quickly and quickly get four unique random numbers?
Any suggestion is welcome.
java random numbers
Sagar gautam
source share