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() {
return new double[10];
}
public static void print(){
System.out.println(String.join(" ", anArray);
}
public static double randomFill() {
return (new Random()).nextInt();
}
public static void main(String args[]) {
// TODO
}
}
I'm struggling to figure out how to fill the array with the random numbers I have generated in the randomFill method. Thanks!
random() returns random double value between 0 and 1 , we multiply it by 100 to get random numbers between 0 to 100 and then we cast it into type int . To store random double values in an array we don't need to cast the double value returned by Math. random() function.
You can use IntStream ints() or DoubleStream doubles() available as of java 8 in Random class. something like this will work, depends if you want double or ints etc.
Random random = new Random();
int[] array = random.ints(100000, 10,100000).toArray();
you can print the array and you'll get 100000 random integers.
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
This seems a little bit like homework. So I'll give you some hints. The good news is that you're almost there! You've done most of the hard work already!
randomFill()
to the current location of the array.Note: Your array is double
, but you are returning int
s from randomFill
. So there's something you need to fix there.
People don't see the nice cool Stream producers all over the Java libs.
public static double[] list(){
return new Random().ints().asDoubleStream().toArray();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With