I have recently started learning about programming mobile applications. I was doing some practice, writing basic programs. First of all I am using LibGDX, so first I test my application on desktop then test it on android.
Somewhere in my program it has to generate 3 random numbers from 0, 1, 2 ( they can be the same numbers as long as they are random ). On desktop my program works fine, it generates 3 random numbers each time i run it. However when i try it on my android phone, all the three numbers are the same. For example 3 trials: My desktop: 0-0-1, 2-1-2, 2-0-1 My phone; 0-0-0, 2-2-2, 0-0-0;
for (int x = 0; x < 3; x++){
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(3);
postNumber(randomNumber);//This function I wrote sends the randomNumber to be drawn on the screen
}
You should initialize the Random()
instance outside your loop - or ideally, just once. (The documentation states that it's thread-safe, so you shouldn't need one per thread or anything like that.)
Basically, it's seeding a new instance of Random
based on the current time... and that current time isn't changing significantly between iterations of the loop. This is a common error, and the Oracle Java implementation fixed it a while ago - it looks like the Android implementation hasn't, yet. But fundamentally it's a problem of your own making, and definitely avoidable by using a single instance of Random
to generate all your numbers.
See more on this question at Stackoverflow