Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...