In your apps (especially in game apps) , you may come across the need to generate random numbers. For generation of psuedo random numbers you can use random class from package java.util
First of all you can construct a random number generator using this
The seed should be unique for better results. You can use current time for that
Time t = new Time();
t.setToNow();
mRandom = new Random(t.toMillis(false));
Now to generate a random number from 0 to n, you can use mRandom.nextInt(n). Make sure that n is not zero.
int rand = mRandom.nextInt(10);
The above line generates a random number between 0 to 9.
Random class also provides other functions such as nextFloat(), nextDouble, nextLong.
First of all you can construct a random number generator using this
mRandom = new Random(seed);
The seed should be unique for better results. You can use current time for that
Time t = new Time();
t.setToNow();
mRandom = new Random(t.toMillis(false));
Now to generate a random number from 0 to n, you can use mRandom.nextInt(n). Make sure that n is not zero.
int rand = mRandom.nextInt(10);
The above line generates a random number between 0 to 9.
Random class also provides other functions such as nextFloat(), nextDouble, nextLong.
Could you please show how the whole java code file looks like with this code implemented. Thanks!
ReplyDeleteHow do i make sure that these random numbers r not repeatetive ???
ReplyDeleteI have been using it many times in my program and I rarely see repeated numbers. When you say something like random.nextInt(100), you do get a random number. If necessary, you can modify the seed by using random.setSeed(long), where you can use the current time as the seed value.
Delete