user6911980
user6911980

Reputation:

Generating random numbers, doesn't return some numbers

Just trying to generate 8 random numbers, but I'm only getting 3 numbers returned.

Code:

import java.util.Random;

public class One{
  public static void main(String[] args){

      Random rand = new Random();
      int[] deciJunc = new  int[8];

      for(int i=0; i<8; i++){
          deciJunc[i] = 1+rand.nextInt(8);
          System.out.println(deciJunc[i]);
      }

  }
}

Output:

3
5
7
3
3
5
7
3

Output:

3
3
3
5
7
7
7
3

Now, I've ran this program like 10 times and it's only giving me these 3 numbers (3,5,7) and I don't understand what's wrong. If I change:

deciJunc[i] = 1+rand.nextInt(8);

to

deciJunc[i] = 4+rand.nextInt(8);

It works fine, I get an output of a good mix like:

8
9
10
4
4
9
9
6

What's wrong with the first one where it only returns the 3 different numbers?

Upvotes: 1

Views: 170

Answers (1)

Pratik Ambani
Pratik Ambani

Reputation: 2570

Not for me Dear!

Please observe my results while running your code for multiple times:

Result 1: 6, 5, 8, 7, 8, 1, 5, 2

Result 2: 8, 1, 7, 3, 8, 6, 8, 5

Still, if you are not satisfied with behavior of java.util.Random class. You may wish to have a look at SecureRandom from java Security package where Random Numbers are generated using Algorithms.

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class SecureRandom {

    public static void main(String[] args) {
        try {
            java.security.SecureRandom secureRandomGenerator = java.security.SecureRandom.getInstance("SHA1PRNG");
            byte[] randomBytes = new byte[128];
            secureRandomGenerator.nextBytes(randomBytes);
            int seedByteCount = 5;
            byte[] seed = secureRandomGenerator.generateSeed(seedByteCount);

            java.security.SecureRandom secureRandom1 = java.security.SecureRandom.getInstance("SHA1PRNG");
            secureRandom1.setSeed(seed);
            java.security.SecureRandom secureRandom2 = java.security.SecureRandom.getInstance("SHA1PRNG");
            secureRandom2.setSeed(seed);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("CustomAlgorithmNotFoundException" + e);
        }
    }
}

Here you can find awesome explaintion about hoe SecureRandom works. Let me know if you need more help with the same.

Upvotes: 1

Related Questions