-
Random numbers
Hi!
I want to generate random numbers between 0-80. The no. generated should be unique that is it should not have been used. I have been trying for it but to no avail. Here is what iam doing:
Code:
int nRand = 0;
int n = 0;
boolean bFlag = true;
while (bFlag && n <= 80)
{
//Generate a random no
nRand = new Random().nextInt(81);
if (...//Now check if the no has already been used)
{
...
//perform some work
bFlag = false;
}
//Increment n. When n > 80 it will show that all no have been used.
++n;
}
The problem with the above code is that nextInt doesnt gen a unique no. For instance lets say nextInt gen 20 and 20 is already used then in all other iterations of the while loop nextInt continues to gen 20 :(, while i want it to generate a unique no (a no which has not been gen before).
Please help.
Regards.
-
Re: Random numbers
The following class generates random numbers within specified limits
public class RandomNumberBounds {
private static void generateRandomNumber() {
int rawNumber;
//change these two for ur limit
int min = 30;
int max = 256;
for (int i = 0; i < 500; i++) {
rawNumber = (int) (Math.random() * (max - min + 1) ) + min;
System.out.println("Random number : " + rawNumber);
}
System.out.println("\n");
}
public static void main(String[] args) {
generateRandomNumber();
}
}
Happy coding!!!!!!
-
Re: Random numbers