Issue
So here is one of the simplest things one might do:
Random rng = new Random();
int a = rng.nextInt(10);
int b = rng.nextInt(10);
So far so good. But we want to avoid having equal a and b, so naturally we do:
Random rng = new Random();
int a = rng.nextInt(10);
int b = rng.nextInt(10);
while (a == b){
b = rng.nextInt(10);
}
However — to my very very very big surprise — the while loop never exits. Never.
I understand that, in theory, with random numbers you could have an infinite sequence of one number. But I've had this code running for 10 minutes now and it hasn't exited the loop.
What's up with this? I'm running JDK 6 Update 16 on the latest Linux Mint.
Solution
Random rng = new Random();
int a = rng.nextInt(10);
int b = rng.nextInt(9);
if (b >= a) ++b;
Problem solved!
Answered By - Mark Byers