-1
 for(int i = 0; i < emojiCnt; i++){

            Random rand = new Random(1000);
            int randNum = rand.nextInt((3) + 1);
            switch (randNum){
                case 1:
                    //Code
                case 2:
                    //Code
                case 3:
                    //Code
                default:
                    //Code
            }
            randNum = rand.nextInt((10) + 1);
        }

Every time I run the code, it gives the same result and is not random? I reassign randNum so that it will go to a random number but it doesn't seem to change?

FreeThaMan
  • 11
  • 1

3 Answers3

1

You seed the RNG with a constant by calling ... = new Random(1000);. With the same seed, one will always get the same sequence of "random numbers". Do not seed (... = new Random();), and the values should be "random".


A comment on randomness and programming:

Without an external entropy generator, a computer is generally not able to generate true randomness. Thus, random number generators operate by using an inital seed to generate a pseudo-random sequence. The sequence normally satisfies all conditions expected by a truly random sequence, but is deterministic once the seed is known. More information can be found on the wikipedia article on Random number generators.

Turing85
  • 18,217
  • 7
  • 33
  • 58
1

Random rand = new Random(1000); tells java to create a Random, based on the initial seed of 1000. This results in random, but still reproducable results.

If you want different values for each execution, use Random rand = new Random(); instead.

slartidan
  • 20,403
  • 15
  • 83
  • 131
-2

Try to use this code to get random numbers:

Random rand = new Random();
int maxNumber = 1000;
rand.nextInt(maxNumber)

This code will bring you random values between 0 and 1000

Cardstdani
  • 4,999
  • 3
  • 12
  • 31
  • So why exactly does the random not need a seed? – FreeThaMan Jul 04 '20 at 18:58
  • Because you set the max number in the nextInt() function – Cardstdani Jul 04 '20 at 18:59
  • So does a seed not do anything?! – FreeThaMan Jul 04 '20 at 19:00
  • Depends on how are you going to implement random in your code, but this is the way I use it, you can find more information about it here: https://docs.oracle.com/javase/8/docs/api/java/util/Random.html – Cardstdani Jul 04 '20 at 19:02
  • This would be a better answer if it explained why the provided code works. Merely writing someone’s code for them may help the poster of the question, but it doesn’t do much to help other readers. – VGR Jul 04 '20 at 22:17