我做了使用随机类来生成一个号码的方法。这些数字被用于填充在阵列中。此方法返回填充阵列。所以,我有这等于返回的数组一些其他的阵列,我做。然而,这些阵列都是相同的,即使他们应该是随机的。
我试着印刷了每个调用随机的,有权根据它调用数组。这给了我不同的阵列。但是,如果我将我的打印到下的所有调用,那么阵列都是一样的。此外,我认为这是一个数组的问题,因为我只是有这个问题,数组。
public static int[] numberGenerator(int[] array) {
Random rand = new Random();
int min = 0;
int max = 0;
int x = 0;
for (int j = 0; j < array.length; j++) {
if (j == 0) {
min = 1;
max = 15;
}
if (j == 1) {
min = 16;
max = 30;
}
if (j == 2) {
min = 31;
max = 45;
}
x = rand.nextInt((max - min) + 1) + min;
array[j] = x;
}
return array;
}
public static void main(String[] args) {
int[] array = {' ', ' ', ' '};
int[] array1 = numberGenerator(array);
int[] array2 = numberGenerator(array);
System.out.println(array1[1]);
System.out.println(array2[1]);
}
}
不同的阵列就是我要找的。
你修改你传递数组到方法。既然你不使用阵列的现有内容,无论如何,这将是最好只传递所需的长度,并创建方法一个新的数组:
public static int[] numberGenerator(int length) {
int[] array = new int[length];
// Rest of method as before
}
然后改变你的main
方法:
public static void main(String[] args) {
int[] array1 = numberGenerator(3);
int[] array2 = numberGenerator(3);
System.out.println(array1[1]);
System.out.println(array2[1]);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句