How can Java store generated random numbers in an array?

You can use a for loop to generate random numbers and store them in an array. The specific code is shown below:

import java.util.Random;

public class RandomNumberArray {
    public static void main(String[] args) {
        int[] randomArray = new int[10];  // 创建一个长度为10的整型数组

        Random random = new Random();
        for (int i = 0; i < randomArray.length; i++) {
            randomArray[i] = random.nextInt(100);  // 生成0到99之间的随机数
        }

        // 打印数组中的元素
        for (int i = 0; i < randomArray.length; i++) {
            System.out.println(randomArray[i]);
        }
    }
}

In the above code, a integer array called randomArray with a length of 10 is first created. Then, a random object is created using the Random class, and random numbers between 0 and 99 are generated using the nextInt(100) method and sequentially stored in the array. Finally, a for loop is used to iterate through the array and print out each element.

Leave a Reply 0

Your email address will not be published. Required fields are marked *