填充随机数字的数组 [英] Fill an array with random numbers

查看:156
本文介绍了填充随机数字的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用构造函数创建一个数组,添加一个方法来打印数组作为序列和方法,以填补与double类型的随机数的数组。

I need to create an array using a constructor, add a method to print the array as a sequence and a method to fill the array with random numbers of the type double.

下面就是我迄今所做的:

Here's what I've done so far:

import java.util.Random;


public class NumberList {


    private static double[] anArray;

    public static double[] list(){
        anArray = new double[10];   
        return anArray;
    }

    public static void print(){
        for(double n: anArray){
        System.out.println(n+" ");
        }
    }


    public static double randomFill(){

    Random rand = new Random();
    int randomNum = rand.nextInt();
    return randomNum;
    }

    public static void main(String args[]) {

    }


}

我竭力要弄清楚如何与我在randomFill方法所产生的随机数填充数组。谢谢!

I'm struggling to figure out how to fill the array with the random numbers i've generated in the randomFill method. Thanks!

推荐答案

您需要添加逻辑来分配随机值用加倍[]数组的 randomFill 方式。

You need to add logic to assign random values to double[] array using randomFill method.

修改

 public static double[] list(){
    anArray = new double[10];   
    return anArray;
 }

 public static double[] list() {
    anArray = new double[10];
    for(int i=0;i<anArray.length;i++)
    {
        anArray[i] = randomFill();
    }
    return anArray;
}

然后就可以调用的方法,包括列表()和生成随机double值,并在控制台打印双[]数组主要方法打印()。

Then you can call methods, including list() and print() in main method to generate random double values and print the double[] array in console.

 public static void main(String args[]) {

list();
print();
 }

的一个结果是,如下所示:

One result is as follows:

-2.89783865E8 
1.605018025E9 
-1.55668528E9 
-1.589135498E9 
-6.33159518E8 
-1.038278095E9 
-4.2632203E8 
1.310182951E9 
1.350639892E9 
6.7543543E7 

这篇关于填充随机数字的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆