JaAnTr JaAnTr - 1 month ago 10
Java Question

Fill an array with random numbers

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[]) {

}


}


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

Answer

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

Change

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

To

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

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 
Comments