Random.nextInt () produces very similar numbers?

I wrote a class to generate a random Int array with numbers between (0-100) in Java:

    import java.util.Random;

    public class RandomClass{
        private Random randNum;

        public RandomClass() {
            randNum = new Random();
        }

        public int[] generateRandomArray(int arraySize){
            int[] theArray = new int[arraySize];
            for(int i = 0; i < arraySize; i++){
                theArray[i] = randNum.nextInt(101);
            }
            return theArray;        
        }
    }

For some reason, when I run my program, I get the same sequence of numbers that repeats in my array every time.

Here is an example showing 3 runs of a program at another time:

Array result: [65, 71, 71, 71, 78, 78, 78, 78, 78, 78]

Array result: [40, 55, 55, 55, 62, 62, 62, 70, 77, 77]

Array result: [56, 56, 73, 73, 73, 73, 77, 77, 77, 77]

Why is this happening? Is it because the Random function is time-based and the loop runs too fast before it can return a new β€œrandom” number? Or some other reason? How to fix it?

+4
source share
1 answer

, , , :

public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
        int[] ints = new RandomClass().generateRandomArray(10);
        System.out.println("RandomClass::main: ints = " + Arrays.toString(ints));
    }
}

. .

+3

All Articles