简体   繁体   English

从1-300生成30个随机数的数组返回全0而不是其他数字

[英]Array to generate 30 random numbers from 1-300 returns all 0s instead of other numbers

I have a problem where I'm trying to fill an array with 30 random integers from the range 1-300 with just a main method and one more method called LOAD(). 我有一个问题,我试图用一个主要方法和另一个称为LOAD()的方法来填充数组1-300范围内的30个随机整数。 For some reason my code below generates an array with my test statement System.out.println("Here are 30 random numbers: " + Arrays.toString(randomThirty)); 由于某种原因,下面的代码使用测试语句System.out.println("Here are 30 random numbers: " + Arrays.toString(randomThirty));生成一个数组System.out.println("Here are 30 random numbers: " + Arrays.toString(randomThirty)); but it's filled with only 0s and no other numbers in all fields. 但在所有字段中仅填充0,没有其他数字。

import java.util.*;

public class randArray
{

public static void main(String args[])
{
     //main method which creates an array to store 30 integers

    int[] randomThirty = new int[30]; //declare and set the array randomThirty to have 30 elements as int type

    System.out.println("Here are 30 random numbers: " + Arrays.toString(randomThirty));

    LOAD(randomThirty); // the job of this method is to populate this array with 30 integers in the range of 1 through 300.

}

public static void LOAD(int[] randomThirty)
{
    // looping through to assign random values from 1 - 300
    for (int i = 0; i < randomThirty.length; i++) {
        randomThirty[i] = (int)(Math.random() * 301); 
}
}

} }

The reason is that you print out the array first, and populate it second. 原因是先打印出数组,然后再填充它。

In other words, LOAD() doesn't get called until after you've printed out the array. 换句话说,直到您打印出数组后,才会调用LOAD()

您正在调用方法之前进行打印....更改调用顺序,它将起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM