如何重新随机化随机数?

问题描述 投票:0回答:1

对于这个程序,我应该随机化 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]);
java arrays basic replit
1个回答
0
投票

您只需在将数字放入数组之前移动

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.