Math.random()和Random::nextInt总是在for循环中给出相同的确切数字
所以我试图用随机数创建一个数组,但是每当我尝试Math.random或创建一个新Random对象并使用它时,我总是多次得到相同的数字。我的代码是这样的:
int[] Array = new int[size];
for (int Y : Array) {
Array[Y] = (int) (Math.random() * 10) + 3;
}
或者这个:
int[] Array = new int[size];
for (int Y: Array) {
Array[Y] = rand.nextInt(30);
}
我得到的输出是:[0][3][3][3][3][3][3][3][3][3][3][3][3][3][3] ][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3]
我还没有设置种子,我在循环外和内都尝试过,但仍然只能得到相同的数字。
回答
您不是指数组的索引,而是指保持不变的特定元素。您必须使用索引循环。
试试这个(对变量使用驼峰式大小写是一个好习惯,所以 'Array' 以小 'a' 开头)
int[] array = new int[size];
for(int i = 0; i < array.length; i++) {
array[i] = rand.nextInt(30);
}
- @JoshMiller The problem is that using the `for (int y : array)` form, `y` will not be an index of the array, it will be an element of the array. Since before the loop you instantiated an array without specifying its content, all the elements where set to `int`'s default value (0), so `y` will always be 0 and you were always setting the value of `array[y]`, that is `array[0]`
THE END
二维码