My goal is to ask the user for an array length and generate a list of random doubles to fill that array out. I don't understand how to get Math.random into my array. I started with a different approach and scrapped it. Why does double random = Math.random() * array; not import a random generator into my array?
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
public class Average
{
public static void main(String[] args)
{
/*Scanner in = new Scanner (System.in);
System.out.println("Please enter your array size: ");
int size = in.nextInt();
int[] awnser = new int[size]; */
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
double[] array = new double[scanner.nextDdouble()];
double random = Math.random() * array;
System.out.println(array.length);
}
}
Why does double random = Math.random() * array; not import a random generator into my array?
You have misunderstood how this class works. Here is a good explanation of what this class does. What I believe you are trying to do is something along the lines of:
Random rand = new Random();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
//create an array with the size entered by the user
double[] array = new double[scanner.nextInt()];
//populate the array with doubles
for(int i =0; i < array.length; i++) {
array[i] = rand.nextDouble();
}
nextDouble
returns a pseudorandom number between 0 and 1.0, so you'll need to multiply it by your upper bound. (i.e if 100 was your upper limit rand.nextDouble() * 100;
)
(Make sure to import
the Random
class)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments