Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

java - How do I generate random doubles in an Array?

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);

    }
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With your current solution you'd need to iterate with a counter starting from 0 and ending before the given size, assigning each array element with a nextDouble invocation.

Multiplying an array object by a number is just not supported in Java.

Here's a Java-8 idiom that you may favor instead:

DoubleStream
    .generate(ThreadLocalRandom.current()::nextDouble)
    .limit(yourGivenSize)
    .toArray();

This will give you a double[] of size yourGivenSize, whose elements are generated randomly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...