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?