对于这个程序,我应该随机化 1 到 50 之间的 1000 个数字,但我意识到我不知道如何重新随机化它。它表示该变量已经定义了
import java.util.Random;
public static void main(String[] args) throws IOException{
// ***** constants *******
int MAX = 1000;
// ***** variables *****
int count = 0;
int num = 0;
//array
int[] array = new int[MAX];
// ***** objects *****
Scanner scanner = new Scanner(System.in); //get input
Random rand = new Random(); ///random number generator object
//generate a ranom integer
int n = rand.nextInt(50);
//changing the range from 0-49 to 1-50
n += 1;
//while loop
while (n != 0 && count < array.length){
array[count++] = n;
int n = rand.nextInt(50);
n += 1;
}
// ***** Print Formatted Output *****
for(int i = 0; i < count; i++){
System.out.println(array[i]);
您只需在将数字放入数组之前移动
n = rand.nextInt(50);
即可。另一个问题是每次运行 while 循环时都会创建一个新的 int n 。相反,做这样的事情:
while (n != 0 && count < array.length){
n = rand.nextInt(50);
array[count++] = n;
n += 1;
}
但即使在这里,我也不认为你正确地迭代了每个点,也许 for 循环可能会更好,像这样
for(int i = 0; i <array.length && n != 0; i++){
n = rand.nextInt(50);
array[i] = n;
}